diff --git a/benchmarks/Relayer.Benchmarks/OutboxEnlistmentBenchmarks.cs b/benchmarks/Relayer.Benchmarks/OutboxEnlistmentBenchmarks.cs index 7e9891045..a363f638b 100644 --- a/benchmarks/Relayer.Benchmarks/OutboxEnlistmentBenchmarks.cs +++ b/benchmarks/Relayer.Benchmarks/OutboxEnlistmentBenchmarks.cs @@ -39,7 +39,7 @@ public void Setup() ]; _record = new(Guid.CreateVersion7(), "events", "benchmark.order;v=1", new OutgoingMessage("orders", new byte[BodySize], headers, new WireString("customer-42")), DateTimeOffset.UtcNow); - _state.Add(_record); + _state.Add(_record, 1); _state.Clear(); } @@ -63,3 +63,30 @@ public void Cleanup() _provider.Dispose(); } } + +/// Measures reusable row ordering when EF contexts interleave sends in one transaction. +[MemoryDiagnoser] +public class SharedTransactionSendOrderBenchmarks +{ + private BufferedOutboxMessage[] _rows = null!; + + [Params(2, 32, 256)] + public int Count { get; set; } + + [GlobalSetup] + public void Setup() + { + _rows = new BufferedOutboxMessage[Count]; + for (var i = 0; i < Count; i++) _rows[i] = new(); + OrderInterleavedRows(); + } + + [Benchmark] + public long OrderInterleavedRows() + { + // Two contexts each append in send order; concatenating them groups even and odd positions. + for (var i = 0; i < Count; i++) _rows[i].EnqueueOrder = i < Count / 2 ? i * 2 : (i - Count / 2) * 2 + 1; + EntityFrameworkCoreOutbox.SortSendOrder(_rows); + return _rows[^1].EnqueueOrder; + } +} diff --git a/docs/decisions.md b/docs/decisions.md index 83971d9d6..cfd81b46a 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -60,7 +60,7 @@ To change a decision, add a new entry that supersedes it rather than editing his | [D47](#d47-sql-server-outbox-transactions-reuse-native-bulk-copy) | SQL Server outbox transactions reuse native bulk copy | Accepted | | [D48](#d48-mysql-enqueue-owns-native-transactions-and-reuses-mysqlbatch) | MySQL enqueue owns native transactions and reuses MySqlBatch | Accepted | | [D49](#d49-sql-server-commit-dispatch-reuses-native-rpc-batches) | SQL Server commit dispatch reuses native RPC batches | Accepted | -| [D50](#d50-ordered-lanes-follow-a-database-assigned-insert-sequence) | Ordered lanes follow a database-assigned insert sequence | Proposed | +| [D50](#d50-ordered-lanes-follow-a-database-assigned-insert-sequence) | Ordered lanes follow a database-assigned insert sequence | Accepted | | [D51](#d51-the-ef-core-consumer-boundary-takes-an-isolation-level-and-replays-conflicts) | The EF Core consumer boundary takes an isolation level and replays conflicts | Proposed | | [D52](#d52-allocations-a-native-api-requires-count-as-native-client-cost) | Allocations a native API requires count as native-client cost | Accepted | @@ -641,7 +641,7 @@ allocations without weakening that boundary. Native execution, materialization a outside the managed command-binding benchmark. **Consequences.** Database failure or uncertain completion rolls back the batch, so accepted sends can replay. -Ordering describes ascending visible UUIDs, not concurrent writers' commit order. When a database connection +Ordering follows the database-assigned insert sequence among visible rows (D50), not concurrent writers' commit order. When a database connection fails while a native request is in flight, that request can arrive late: neither cancellation nor the lease can retract it. Native ordering semantics and the at-least-once contract remain unchanged. Strict fencing of native requests requires broker support and is not emulated. Idempotent consumers remain necessary. @@ -984,7 +984,7 @@ benchmarks isolate Relayer's reusable copy/swap/group work; database and native ## D50. Ordered lanes follow a database-assigned insert sequence -**Status.** Proposed; not implemented. Tracked by [#353](https://github.com/thomhurst/Relayer/issues/353). +**Status.** Accepted. Implemented for PostgreSQL; SQL Server and MySQL ordered dispatch must adopt the same rule in #330 and #344. **Context.** D34 reads each lane in ascending `id` order. The `id` is a UUIDv7 created on the application host when the message is sent, while its row is inserted at flush, immediately before commit (D31, D32). @@ -995,8 +995,8 @@ only concurrent writers from its ordering guarantee; these transactions are not **Decision.** Refine D34's read order while retaining its lane leases, locks, deadlines and fencing. - The outbox table gains `seq`, a database-assigned identity value set when the row is inserted. -- Ordered lanes read and index pending rows by `(lane, seq)`. The parked-key anti-join compares `seq`. -- One transaction's rows are inserted in send order, so their `seq` values keep that order. +- Ordered lanes read and index pending rows by `(lane, seq)`. The parked-key anti-join compares `seq`. Unordered pending rows keep a partial UUID index and their existing read/recovery cursors. +- One transaction's rows are inserted in send order, so their `seq` values keep that order. PostgreSQL uses `UNNEST WITH ORDINALITY ORDER BY position`; shared EF contexts merge their reusable rows by a scope-local enqueue position before insertion. - `id` remains the stable message identity for the inbox, native message IDs and fenced claims. - Other database stores adopt the same rule with their native identity or sequence feature. @@ -1006,7 +1006,7 @@ their `seq` values also follow commit order. A sequence is non-transactional: it business transaction can wait on, and it cannot raise a serialization failure. Transactions that are genuinely concurrent still have no defined order, and a row committed late can still be dispatched after a higher `seq`; idempotent, version-guarded consumers remain necessary. Existing tables need an explicit -SQL migration (D30). Identity values can have gaps. +SQL migration (D30). The upgrade preserves existing rows' former UUID order because historical insertion order is unavailable; it must run with writers and dispatchers stopped, in one application-owned transaction. Identity values can have gaps; keep the sequence's default cache of one and do not reset it. **Alternatives rejected.** - A per-key advisory lock held from flush to commit gives strict commit order, but makes same-key writers queue diff --git a/docs/design.md b/docs/design.md index 8d2356d90..41c745b9b 100644 --- a/docs/design.md +++ b/docs/design.md @@ -451,7 +451,7 @@ The outbox is the area where every existing library has had correctness bugs, so - A message is written in the **same database transaction** as your business data. It is dispatched if and only if that transaction commits. - Delivery is at-least-once. The message ID (UUIDv7) is stable across retries and dispatches, so the consumer-side inbox deduplicates. -- Ordering is preserved per ordering key when the route declares it (Kafka key, ASB session, SQS FIFO message group). Lanes currently follow send-time UUIDv7 order, so instances with different clocks can reorder sequential commits; D50 proposes a database-assigned insert sequence ([#353](https://github.com/thomhurst/Relayer/issues/353)). +- Ordering is preserved per ordering key when the route declares it (Kafka key, ASB session, SQS FIFO message group). Lanes follow a database-assigned insert sequence (D50), preserving sequential transactions' commit order independently of host clocks. Genuinely concurrent transactions have no defined order. - A poison outbox row never blocks unrelated messages. - The design is safe with any number of instances. There is no double dispatch under normal operation, no cleanup race between instances, and no per-replica background-job storms. @@ -466,6 +466,7 @@ The outbox is the area where every existing library has had correctness bugs, so ``` relayer_outbox id uuid (v7) primary key + seq bigint database-assigned insert identity (outbox only) lane integer hash(ordering_key) % lanes, or null when unordered ordering_key text nullable transport text @@ -482,7 +483,9 @@ relayer_outbox claim_token uuid nullable, unique per dispatch attempt claim_expires_at timestamptz nullable -index (lane, id) where status is pending -- partial/filtered where the database supports it +index (lane, seq) where status is pending and lane is not null -- partial/filtered where the database supports it +index (id) where status is pending and lane is null +index (lane, ordering_key, seq) where status is parked index (deliver_at) where deliver_at is not null relayer_leases @@ -492,7 +495,7 @@ relayer_leases ``` PostgreSQL ships one embedded SQL creation script, exposed by the database CLI and an application-owned -EF Core migration operation (D30). Other database scripts remain planned. Indexes are created by default +EF Core migration operation (D30). D50 adds an explicit insert-sequence SQL upgrade for existing PostgreSQL tables; creation does not upgrade them. Existing rows keep their former UUID order because historical insertion order cannot be recovered. Other database stores' ordered workers adopt native identity/sequence ordering when implemented. Indexes are created by default (CAP #1599). Tables can be prefixed and given a schema (NSB.Persistence.Sql #2093). See [schema deployment and migration usage](../website/docs/reference/postgres-schema.md). @@ -513,7 +516,7 @@ live token, so a stale dispatcher cannot mutate a reclaimed row. PostgreSQL sche There are two paths, each chosen per message based on whether its route is ordered: 1. **Unordered messages — direct dispatch.** After commit, the instance that committed dispatches immediately, in the background, without waiting for a poll. It claims an eligible row with a conditional update that sets a fresh claim token and expiry only when no live claim exists. Completion, renewal and failure updates require that token and an unexpired claim. This prevents concurrent claims and stale database mutations; a crash or a broker send that outlives its claim can still duplicate delivery, as allowed by the at-least-once guarantee. Latency equals the broker round trip (fixes the latency of polling designs, SlimMessageBus #275). -2. **Ordered messages — lane leases.** Rows are hashed into N lanes (default 32). Instances lease lanes through `relayer_leases` with heartbeats and fair-share rebalancing as instances join and leave. A lane owner reads its lane in `id` order with a simple indexed range scan. There are no `SKIP LOCKED` scans across the whole table, and connected owners do not overlap. D34 specifies transaction locks, deadlines and the at-least-once/native-send failure boundary; ordering follows visible UUID order rather than concurrent transaction commit order. D50 (proposed) replaces UUID order with an insert sequence. Each ordered worker retains at most 256 successful endpoint capability lookups with FIFO eviction. An evicted endpoint is resolved and validated again before its next native send; failed lookups never displace valid entries. +2. **Ordered messages — lane leases.** Rows are hashed into N lanes (default 32). Instances lease lanes through `relayer_leases` with heartbeats and fair-share rebalancing as instances join and leave. A lane owner reads its lane in database-assigned `seq` order with a simple indexed range scan. There are no `SKIP LOCKED` scans across the whole table, and connected owners do not overlap. D34 specifies transaction locks, deadlines and the at-least-once/native-send failure boundary; D50 preserves sequential commit order using insertion sequence, while genuinely concurrent transactions have no defined order. Each ordered worker retains at most 256 successful endpoint capability lookups with FIFO eviction. An evicted endpoint is resolved and validated again before its next native send; failed lookups never displace valid entries. The implemented PostgreSQL direct path transfers reusable buffers after EF commit to an explicitly named hosted worker (D33). It claims each native group of due unordered rows with one conditional statement, diff --git a/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutbox.cs b/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutbox.cs index 99e6059bb..668429f3a 100644 --- a/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutbox.cs +++ b/src/Relayer.Outbox.EntityFrameworkCore/EntityFrameworkCoreOutbox.cs @@ -1,4 +1,5 @@ using System.Data.Common; +using System.Runtime.InteropServices; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using Relayer.Outbox.PostgreSql; @@ -12,6 +13,9 @@ internal sealed class EntityFrameworkCoreOutbox(bool supportsScheduling = false, private readonly List _contexts = []; private readonly PostgreSqlOutboxBatch _batch = new(); private Selection? _selection; + private long _enqueueOrder; + private readonly List _sharedRows = []; + private static readonly Comparison SendOrder = static (left, right) => left.EnqueueOrder.CompareTo(right.EnqueueOrder); private OutboxConfiguration? _activeConfiguration; public bool SupportsScheduling => _activeConfiguration?.SupportsScheduling ?? supportsScheduling; @@ -32,7 +36,7 @@ public ValueTask EnlistAsync(OutboxRecord record, CancellationToken cancellation { cancellationToken.ThrowIfCancellationRequested(); var target = Target() ?? throw new InvalidOperationException("Select an EF Core outbox context or begin an EF Core transaction before sending."); - target.Add(record); + target.Add(record, checked(++_enqueueOrder)); return ValueTask.CompletedTask; } @@ -120,6 +124,7 @@ internal void Invalidate(DbTransaction transaction) { OutboxConfiguration? configuration = null; var count = 0; + var participants = 0; foreach (var state in _contexts) { if (!ReferenceEquals(state.Transaction, transaction)) continue; @@ -128,15 +133,31 @@ internal void Invalidate(DbTransaction transaction) throw new InvalidOperationException("DbContexts sharing a transaction must use identical outbox schema, prefix and lane settings."); configuration = state.Configuration; count = checked(count + state.Count); + if (state.Count != 0) participants++; } if (count == 0) return null; _batch.Prepare(transaction, configuration!.InsertSql); + // A single context already buffers in send order. Shared transactions can interleave + // sends across contexts; merge their reusable rows before the database assigns seq. foreach (var state in _contexts) if (ReferenceEquals(state.Transaction, transaction)) - for (var i = 0; i < state.Count; i++) _batch.Add(state.Rows[i]); + for (var i = 0; i < state.Count; i++) + if (participants == 1) _batch.Add(state.Rows[i]); + else _sharedRows.Add(state.Rows[i]); + if (participants > 1) + { + try + { + SortSendOrder(CollectionsMarshal.AsSpan(_sharedRows)); + for (var i = 0; i < _sharedRows.Count; i++) _batch.Add(_sharedRows[i]); + } + finally { _sharedRows.Clear(); } + } return _batch; } + internal static void SortSendOrder(Span rows) => rows.Sort(SendOrder); + public void Dispose() { foreach (var state in _contexts) state.Clear(); @@ -204,7 +225,7 @@ internal void EnsureTransactionAvailable() throw new InvalidOperationException("This DbContext no longer participates in its live shared transaction. Complete that transaction before reusing the context."); } - internal void Add(OutboxRecord record) + internal void Add(OutboxRecord record, long enqueueOrder) { if (Failed) throw new InvalidOperationException("Roll back the failed outbox transaction before sending again."); if (record.Message.DeliverAt is not null && !(record.Message.OrderingKey is not null @@ -213,6 +234,7 @@ internal void Add(OutboxRecord record) BufferedOutboxMessage.Validate(record); if (Count == Rows.Count) Rows.Add(new()); Rows[Count].Copy(record, Configuration.Lanes); + Rows[Count].EnqueueOrder = enqueueOrder; Count++; } diff --git a/src/Relayer.Outbox.PostgreSql/InsertSequenceMigration.sql b/src/Relayer.Outbox.PostgreSql/InsertSequenceMigration.sql new file mode 100644 index 000000000..db0827d72 --- /dev/null +++ b/src/Relayer.Outbox.PostgreSql/InsertSequenceMigration.sql @@ -0,0 +1,15 @@ +-- Run once, in one transaction, with application writers and dispatchers stopped. +-- Preserve the old UUID order for existing rows; historical insert order is unavailable. +LOCK TABLE {{schema}}.{{outbox}} IN ACCESS EXCLUSIVE MODE; +ALTER TABLE {{schema}}.{{outbox}} ADD COLUMN seq bigint; +WITH numbered AS (SELECT id, row_number() OVER (ORDER BY id) AS position FROM {{schema}}.{{outbox}}) +UPDATE {{schema}}.{{outbox}} AS target SET seq = numbered.position FROM numbered WHERE target.id = numbered.id; +ALTER TABLE {{schema}}.{{outbox}} ALTER COLUMN seq SET NOT NULL; +ALTER TABLE {{schema}}.{{outbox}} ALTER COLUMN seq ADD GENERATED ALWAYS AS IDENTITY; +SELECT setval(pg_get_serial_sequence({{outbox_literal}}, 'seq'), COALESCE(max(seq), 1), count(*) > 0) +FROM {{schema}}.{{outbox}}; +DROP INDEX {{schema}}.{{outbox_pending_idx}}; +DROP INDEX {{schema}}.{{outbox_parked_idx}}; +CREATE INDEX {{outbox_pending_idx}} ON {{schema}}.{{outbox}} (lane, seq) WHERE status = 'pending' AND lane IS NOT NULL; +CREATE INDEX {{outbox_unordered_idx}} ON {{schema}}.{{outbox}} (id) WHERE status = 'pending' AND lane IS NULL; +CREATE INDEX {{outbox_parked_idx}} ON {{schema}}.{{outbox}} (lane, ordering_key, seq) WHERE status = 'parked'; diff --git a/src/Relayer.Outbox.PostgreSql/PostgreSqlOrderedLane.cs b/src/Relayer.Outbox.PostgreSql/PostgreSqlOrderedLane.cs index e6e698be6..9ee19b9c5 100644 --- a/src/Relayer.Outbox.PostgreSql/PostgreSqlOrderedLane.cs +++ b/src/Relayer.Outbox.PostgreSql/PostgreSqlOrderedLane.cs @@ -22,9 +22,9 @@ internal PostgreSqlOrderedLane(NpgsqlDataSource source, PostgreSqlOutboxOptions var table = PostgreSqlOutboxSchema.QuoteIdentifier(options.Schema ?? "public") + "." + PostgreSqlOutboxSchema.QuoteIdentifier(options.TablePrefix + "outbox"); // Read scheduled and claimed heads too. Parked keys are excluded without parking the rest of the lane. - _read = $"SELECT id, transport, message_type, destination, body, headers, ordering_key, deliver_at, created_at, lane, attempts, last_error, tenant_id FROM {table} AS pending WHERE lane = @lane AND status = 'pending' AND NOT EXISTS (SELECT 1 FROM {table} AS parked WHERE parked.lane = @lane AND parked.status = 'parked' AND parked.ordering_key = pending.ordering_key AND parked.id < pending.id) ORDER BY id LIMIT @limit"; + _read = $"SELECT id, transport, message_type, destination, body, headers, ordering_key, deliver_at, created_at, lane, attempts, last_error, tenant_id FROM {table} AS pending WHERE lane = @lane AND status = 'pending' AND NOT EXISTS (SELECT 1 FROM {table} AS parked WHERE parked.lane = @lane AND parked.status = 'parked' AND parked.ordering_key = pending.ordering_key AND parked.seq < pending.seq) ORDER BY seq LIMIT @limit"; // Probe only each assigned lane's first non-parked head. Re-read under the lease lock before sending. - _ready = $"SELECT requested.lane FROM unnest(@lanes) AS requested(lane) CROSS JOIN LATERAL (SELECT deliver_at, claim_expires_at FROM {table} AS pending WHERE pending.lane = requested.lane AND status = 'pending' AND NOT EXISTS (SELECT 1 FROM {table} AS parked WHERE parked.lane = requested.lane AND parked.status = 'parked' AND parked.ordering_key = pending.ordering_key AND parked.id < pending.id) ORDER BY id LIMIT 1) AS head WHERE (head.deliver_at IS NULL OR head.deliver_at <= clock_timestamp()) AND (head.claim_expires_at IS NULL OR head.claim_expires_at <= clock_timestamp())"; + _ready = $"SELECT requested.lane FROM unnest(@lanes) AS requested(lane) CROSS JOIN LATERAL (SELECT deliver_at, claim_expires_at FROM {table} AS pending WHERE pending.lane = requested.lane AND status = 'pending' AND NOT EXISTS (SELECT 1 FROM {table} AS parked WHERE parked.lane = requested.lane AND parked.status = 'parked' AND parked.ordering_key = pending.ordering_key AND parked.seq < pending.seq) ORDER BY seq LIMIT 1) AS head WHERE (head.deliver_at IS NULL OR head.deliver_at <= clock_timestamp()) AND (head.claim_expires_at IS NULL OR head.claim_expires_at <= clock_timestamp())"; var fenced = "id = @id AND claim_token = @token AND claim_expires_at > clock_timestamp()"; _claim = CreateMutation($"UPDATE {table} SET claim_token = @token, claim_expires_at = clock_timestamp() + @duration WHERE id = @id AND status = 'pending' AND (deliver_at IS NULL OR deliver_at <= clock_timestamp()) AND (claim_expires_at IS NULL OR claim_expires_at <= clock_timestamp())"); _claim.Parameters.Add(new NpgsqlParameter("duration", NpgsqlDbType.Interval) { TypedValue = duration }); diff --git a/src/Relayer.Outbox.PostgreSql/PostgreSqlOutboxBatch.cs b/src/Relayer.Outbox.PostgreSql/PostgreSqlOutboxBatch.cs index 6b53eee10..8452cd8d9 100644 --- a/src/Relayer.Outbox.PostgreSql/PostgreSqlOutboxBatch.cs +++ b/src/Relayer.Outbox.PostgreSql/PostgreSqlOutboxBatch.cs @@ -13,7 +13,8 @@ INSERT INTO {table} (id, lane, ordering_key, transport, destination, message_type, headers, body, created_at, deliver_at, tenant_id) SELECT id, lane, convert_from(key, 'UTF8'), transport, destination, type, headers, body, created, delivery, tenant FROM unnest(@ids, @lanes, @keys, @transports, @destinations, @types, @headers, @bodies, @created, @delivery, @tenants) - AS rows(id, lane, key, transport, destination, type, headers, body, created, delivery, tenant) + WITH ORDINALITY AS rows(id, lane, key, transport, destination, type, headers, body, created, delivery, tenant, position) + ORDER BY position """; private readonly List _ids = []; diff --git a/src/Relayer.Outbox.PostgreSql/PostgreSqlOutboxSchema.cs b/src/Relayer.Outbox.PostgreSql/PostgreSqlOutboxSchema.cs index 896fc34e1..5d31bdbbb 100644 --- a/src/Relayer.Outbox.PostgreSql/PostgreSqlOutboxSchema.cs +++ b/src/Relayer.Outbox.PostgreSql/PostgreSqlOutboxSchema.cs @@ -8,12 +8,21 @@ public static class PostgreSqlOutboxSchema /// Returns idempotent SQL for a new schema. This does not upgrade existing table definitions. /// Null schema means public. Identifiers are quoted and must fit PostgreSQL's 63-byte limit. public static string CreateScript(PostgreSqlOutboxOptions? options = null) + => Render("Schema.sql", options); + + /// Returns SQL to upgrade a pre-sequence outbox table. Stop writers and dispatchers first. + /// Existing rows retain their former UUID order; historical insertion order cannot be recovered. + /// Run once in an application-owned migration transaction before starting upgraded workers. + public static string CreateInsertSequenceMigrationScript(PostgreSqlOutboxOptions? options = null) + => Render("InsertSequenceMigration.sql", options); + + private static string Render(string resource, PostgreSqlOutboxOptions? options) { options ??= new PostgreSqlOutboxOptions(); var schema = QuoteIdentifier(options.Schema ?? "public"); ArgumentNullException.ThrowIfNull(options.TablePrefix); using var stream = typeof(PostgreSqlOutboxSchema).Assembly.GetManifestResourceStream( - "Relayer.Outbox.PostgreSql.Schema.sql")!; + "Relayer.Outbox.PostgreSql." + resource)!; using var reader = new StreamReader(stream); var template = reader.ReadToEnd(); @@ -30,7 +39,12 @@ public static string CreateScript(PostgreSqlOutboxOptions? options = null) result.Append(template, position, start - position); var end = template.IndexOf("}}", start, StringComparison.Ordinal); var token = template[(start + 2)..end]; - result.Append(token == "schema" ? schema : QuoteIdentifier(options.TablePrefix + token)); + result.Append(token switch + { + "schema" => schema, + "outbox_literal" => "'" + (schema + "." + QuoteIdentifier(options.TablePrefix + "outbox")).Replace("'", "''", StringComparison.Ordinal) + "'", + _ => QuoteIdentifier(options.TablePrefix + token) + }); position = end + 2; } return result.ToString(); diff --git a/src/Relayer.Outbox.PostgreSql/Relayer.Outbox.PostgreSql.csproj b/src/Relayer.Outbox.PostgreSql/Relayer.Outbox.PostgreSql.csproj index 28bc8cfea..fd0a6ac73 100644 --- a/src/Relayer.Outbox.PostgreSql/Relayer.Outbox.PostgreSql.csproj +++ b/src/Relayer.Outbox.PostgreSql/Relayer.Outbox.PostgreSql.csproj @@ -7,6 +7,7 @@ + diff --git a/src/Relayer.Outbox.PostgreSql/Schema.sql b/src/Relayer.Outbox.PostgreSql/Schema.sql index dfc725b89..e2cca0239 100644 --- a/src/Relayer.Outbox.PostgreSql/Schema.sql +++ b/src/Relayer.Outbox.PostgreSql/Schema.sql @@ -2,6 +2,7 @@ CREATE SCHEMA IF NOT EXISTS {{schema}}; CREATE TABLE IF NOT EXISTS {{schema}}.{{outbox}} ( id uuid PRIMARY KEY CHECK (id <> '00000000-0000-0000-0000-000000000000'), + seq bigint GENERATED ALWAYS AS IDENTITY, lane integer CHECK (lane >= 0), ordering_key text, transport text NOT NULL, @@ -20,9 +21,11 @@ CREATE TABLE IF NOT EXISTS {{schema}}.{{outbox}} ( CHECK ((claim_token IS NULL) = (claim_expires_at IS NULL)) ); -CREATE INDEX IF NOT EXISTS {{outbox_pending_idx}} ON {{schema}}.{{outbox}} (lane, id) - WHERE status = 'pending'; -CREATE INDEX IF NOT EXISTS {{outbox_parked_idx}} ON {{schema}}.{{outbox}} (lane, ordering_key, id) +CREATE INDEX IF NOT EXISTS {{outbox_pending_idx}} ON {{schema}}.{{outbox}} (lane, seq) + WHERE status = 'pending' AND lane IS NOT NULL; +CREATE INDEX IF NOT EXISTS {{outbox_unordered_idx}} ON {{schema}}.{{outbox}} (id) + WHERE status = 'pending' AND lane IS NULL; +CREATE INDEX IF NOT EXISTS {{outbox_parked_idx}} ON {{schema}}.{{outbox}} (lane, ordering_key, seq) WHERE status = 'parked'; CREATE INDEX IF NOT EXISTS {{outbox_scheduled_idx}} ON {{schema}}.{{outbox}} (deliver_at) WHERE deliver_at IS NOT NULL; diff --git a/src/Relayer/Sending/BufferedOutboxMessage.cs b/src/Relayer/Sending/BufferedOutboxMessage.cs index 1b7d07afc..eac5e975c 100644 --- a/src/Relayer/Sending/BufferedOutboxMessage.cs +++ b/src/Relayer/Sending/BufferedOutboxMessage.cs @@ -11,6 +11,8 @@ internal sealed class BufferedOutboxMessage internal string Destination { get; private set; } = ""; internal string MessageType { get; private set; } = ""; internal Guid Id { get; private set; } + // Scope-local enqueue position when several EF contexts share one transaction. + internal long EnqueueOrder { get; set; } internal DateTimeOffset CreatedAt { get; private set; } internal string? TenantId { get; private set; } internal DateTimeOffset? DeliverAt { get; private set; } diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/AdoNetEnlistmentTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/AdoNetEnlistmentTests.cs index b69839da9..f8dde3958 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/AdoNetEnlistmentTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/AdoNetEnlistmentTests.cs @@ -15,6 +15,25 @@ namespace Relayer.Outbox.PostgreSql.Tests; public class AdoNetEnlistmentTests { + [Test] + public async Task Batch_assigns_insert_sequence_in_enqueue_order_instead_of_UUID_order() + { + await using var database = new Database(); + await database.Start(); + await using var provider = database.Services(); + await using var scope = provider.CreateAsyncScope(); + var outbox = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await outbox.BeginTransactionAsync(database.Source); + var first = Guid.Parse("01900000-0000-7000-8000-000000000002"); + var second = Guid.Parse("01900000-0000-7000-8000-000000000001"); + await outbox.EnlistAsync(Record() with { Id = first }, default); + await outbox.EnlistAsync(Record() with { Id = second }, default); + await transaction.CommitAsync(); + await using var connection = await database.Source.OpenConnectionAsync(); + var ids = await connection.QueryAsync($"SELECT id FROM {Database.Table} ORDER BY seq"); + await Assert.That(ids.SequenceEqual([first, second])).IsTrue(); + } + [Test] [Arguments(false)] [Arguments(true)] diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/DatabaseSchemaTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/DatabaseSchemaTests.cs index 40ab60822..e18acca54 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/DatabaseSchemaTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/DatabaseSchemaTests.cs @@ -42,11 +42,53 @@ public async Task Scripts_are_idempotent_and_shared_with_EF_and_health_queries() } } + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Insert_sequence_migration_preserves_old_UUID_order_and_continues_after_existing_rows(bool populated) + { + await using var fixture = new PostgreSqlFixture(); + await fixture.StartAsync(); + await using var connection = new NpgsqlConnection(fixture.ConnectionString); + await connection.OpenAsync(); + var options = new PostgreSqlOutboxOptions { Schema = "quote'\";--{{schema}}", TablePrefix = "{{outbox}}_'" }; + var oldSchema = PostgreSqlOutboxSchema.CreateScript(options) + .Replace(" seq bigint GENERATED ALWAYS AS IDENTITY,\n", "", StringComparison.Ordinal) + .Replace("(lane, seq)", "(lane, id)", StringComparison.Ordinal) + .Replace(" AND lane IS NOT NULL", "", StringComparison.Ordinal) + .Replace("(lane, ordering_key, seq)", "(lane, ordering_key, id)", StringComparison.Ordinal); + await Execute(connection, oldSchema); + await Execute(connection, "DROP INDEX " + Table(options, "outbox_unordered_idx")); + var table = Table(options, "outbox"); + var insert = $"INSERT INTO {table} (id, transport, destination, message_type, headers, body, created_at) VALUES "; + const string rest = ", 'events', 'orders', 'probe', ''::bytea, ''::bytea, clock_timestamp())"; + if (populated) + { + await Execute(connection, insert + "('01900000-0000-7000-8000-000000000002'" + rest); + await Execute(connection, insert + "('01900000-0000-7000-8000-000000000001'" + rest); + } + await using (var transaction = await connection.BeginTransactionAsync()) + { + await Execute(connection, PostgreSqlOutboxSchema.CreateInsertSequenceMigrationScript(options)); + await transaction.CommitAsync(); + } + await Execute(connection, insert + "('01900000-0000-7000-8000-000000000003'" + rest); + await Assert.That(await Scalar(connection, $"SELECT seq FROM {table} WHERE id = '01900000-0000-7000-8000-000000000003'")) + .IsEqualTo(populated ? 3L : 1L); + if (populated) + await Assert.That(await Scalar(connection, $"SELECT string_agg(id::text, ',' ORDER BY seq) FROM {table}")) + .IsEqualTo("01900000-0000-7000-8000-000000000001,01900000-0000-7000-8000-000000000002,01900000-0000-7000-8000-000000000003"); + await VerifyCatalog(connection, options); + await Assert.That(await Scalar(connection, + $"SELECT attidentity::text FROM pg_attribute WHERE attrelid = '{table.Replace("'", "''", StringComparison.Ordinal)}'::regclass AND attname = 'seq'")) + .IsEqualTo("a"); + } + private static async Task VerifyCatalog(NpgsqlConnection connection, PostgreSqlOutboxOptions options) { var expected = new Dictionary { - ["outbox"] = ["id:uuid", "lane:integer", "ordering_key:text", "transport:text", "destination:text", "message_type:text", + ["outbox"] = ["id:uuid", "seq:bigint", "lane:integer", "ordering_key:text", "transport:text", "destination:text", "message_type:text", "headers:bytea", "body:bytea", "created_at:timestamp with time zone", "deliver_at:timestamp with time zone", "attempts:integer", "last_error:text", "tenant_id:text", "status:text", "claim_token:uuid", "claim_expires_at:timestamp with time zone"], ["outbox_dead"] = ["id:uuid", "lane:integer", "ordering_key:text", "transport:text", "destination:text", "message_type:text", @@ -58,12 +100,12 @@ private static async Task VerifyCatalog(NpgsqlConnection connection, PostgreSqlO foreach (var (table, columns) in expected) { await using var command = new NpgsqlCommand(""" - SELECT string_agg(column_name || ':' || data_type, ',' ORDER BY ordinal_position) + SELECT string_agg(column_name || ':' || data_type, ',' ORDER BY column_name) FROM information_schema.columns WHERE table_schema = @schema AND table_name = @table """, connection); command.Parameters.AddWithValue("schema", options.Schema ?? "public"); command.Parameters.AddWithValue("table", options.TablePrefix + table); - await Assert.That((string)(await command.ExecuteScalarAsync())!).IsEqualTo(string.Join(',', columns)); + await Assert.That((string)(await command.ExecuteScalarAsync())!).IsEqualTo(string.Join(',', columns.Order(StringComparer.Ordinal))); } await using var indexes = new NpgsqlCommand("SELECT indexdef FROM pg_indexes WHERE schemaname = @schema AND tablename = @table", connection); indexes.Parameters.AddWithValue("schema", options.Schema ?? "public"); @@ -71,10 +113,11 @@ SELECT string_agg(column_name || ':' || data_type, ',' ORDER BY ordinal_position await using var reader = await indexes.ExecuteReaderAsync(); var definitions = new List(); while (await reader.ReadAsync()) definitions.Add(reader.GetString(0)); - await Assert.That(definitions.Count).IsEqualTo(4); - await Assert.That(definitions.Any(x => x.Contains("(lane, id) WHERE (status = 'pending'::text)"))).IsTrue(); + await Assert.That(definitions.Count).IsEqualTo(5); + await Assert.That(definitions.Any(x => x.Contains("(lane, seq) WHERE ((status = 'pending'::text) AND (lane IS NOT NULL))"))).IsTrue(); + await Assert.That(definitions.Any(x => x.Contains("(id) WHERE ((status = 'pending'::text) AND (lane IS NULL))"))).IsTrue(); await Assert.That(definitions.Any(x => x.Contains("(deliver_at) WHERE (deliver_at IS NOT NULL)"))).IsTrue(); - await Assert.That(definitions.Any(x => x.Contains("(lane, ordering_key, id) WHERE (status = 'parked'::text)"))).IsTrue(); + await Assert.That(definitions.Any(x => x.Contains("(lane, ordering_key, seq) WHERE (status = 'parked'::text)"))).IsTrue(); } private static async Task VerifyRowsAndHealth(NpgsqlConnection connection, PostgreSqlOutboxOptions options) diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/EnlistmentTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/EnlistmentTests.cs index 1bd7afc60..3fb8d3551 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/EnlistmentTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/EnlistmentTests.cs @@ -166,13 +166,16 @@ public async Task Multiple_contexts_select_their_owner_and_shared_transactions_u await joined.Database.UseTransactionAsync(shared.GetDbTransaction()); using (orders.EnlistRelayerOutbox()) await sender.SendAsync(new Probe(5)); using (joined.EnlistRelayerOutbox()) await sender.SendAsync(new Probe(6)); + using (orders.EnlistRelayerOutbox()) await sender.SendAsync(new Probe(7)); orders.Add(new Order { Id = 30 }); joined.Add(new Order { Id = 40 }); await orders.SaveChangesAsync(); await joined.SaveChangesAsync(); await Assert.That(await database.Scalar("SELECT count(*) FROM orders")).IsEqualTo(1L); await shared.CommitAsync(); - await Assert.That(await database.Count()).IsEqualTo(4L); + await Assert.That(await database.Count()).IsEqualTo(5L); + await Assert.That(await database.Scalar($"SELECT (string_agg(get_byte(body, 0)::text, ',' ORDER BY seq) = '1,3,5,6,7')::int::bigint FROM {Database.Table}")) + .IsEqualTo(1L); await Assert.That(await database.Scalar("SELECT count(*) FROM batch_log")).IsEqualTo(3L); await Assert.That(await database.Scalar("SELECT count(*) FROM orders")).IsEqualTo(3L); } diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/OrderedDispatchTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/OrderedDispatchTests.cs index 1d91b7d37..10fc0e37d 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/OrderedDispatchTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/OrderedDispatchTests.cs @@ -14,6 +14,53 @@ namespace Relayer.Outbox.PostgreSql.Tests; public class OrderedDispatchTests { + [Test] + public async Task Sequential_commits_dispatch_in_insert_order_even_when_later_UUID_is_smaller() + { + await using var fixture = new PostgreSqlFixture(); + await fixture.StartAsync(); + await using var source = NpgsqlDataSource.Create(fixture.ConnectionString); + await PostgreSqlOutboxStoreTests.CreateSchema(source); + // Each insert commits before the next begins; both rows share the same key. + await Insert(source, Id(2), 0); + await Insert(source, Id(1), 0); + var transport = new RecordingTransport(); + using var worker = Worker(source, transport); + await Assert.That(await worker.DispatchLaneAsync(0, default)).IsEqualTo(2); + await Assert.That(transport.Ids.SequenceEqual([Id(2), Id(1)])).IsTrue(); + } + + [Test] + public async Task Parked_key_barrier_and_ready_probe_follow_insert_sequence_instead_of_UUID() + { + await using var fixture = new PostgreSqlFixture(); + await fixture.StartAsync(); + await using var source = NpgsqlDataSource.Create(fixture.ConnectionString); + await PostgreSqlOutboxStoreTests.CreateSchema(source); + await Insert(source, Id(3), 0); + await Insert(source, Id(2), 0); + await Insert(source, Id(1), 0); + await using (var park = source.CreateCommand("UPDATE relayer_outbox SET status = 'parked' WHERE id = @id")) + { + park.Parameters.AddWithValue("id", Id(2)); + await park.ExecuteNonQueryAsync(); + } + using var lane = new PostgreSqlOrderedLane(source, new() { Lanes = 1 }, TimeSpan.FromSeconds(30)); + var ready = new bool[1]; + await lane.FindReadyAsync([true], ready, default); + await Assert.That(ready[0]).IsTrue(); + var transport = new RecordingTransport(); + using var worker = Worker(source, transport); + await Assert.That(await worker.DispatchLaneAsync(0, default)).IsEqualTo(1); + await Assert.That(transport.Ids.SequenceEqual([Id(3)])).IsTrue(); + await lane.FindReadyAsync([true], ready, default); + await Assert.That(ready[0]).IsFalse(); + await using (var unpark = source.CreateCommand("UPDATE relayer_outbox SET status = 'pending'")) + await unpark.ExecuteNonQueryAsync(); + await Assert.That(await worker.DispatchLaneAsync(0, default)).IsEqualTo(2); + await Assert.That(transport.Ids.SequenceEqual([Id(3), Id(2), Id(1)])).IsTrue(); + } + [Test] public async Task Named_immutable_options_bind_independently_and_registration_validates() { diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/SchemaTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/SchemaTests.cs index e7d1bd50b..f74943fb4 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/SchemaTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/SchemaTests.cs @@ -28,6 +28,8 @@ public async Task Cli_and_EF_migration_use_the_same_embedded_script() await Assert.That(exit).IsEqualTo(0); await Assert.That(output.ToString()).IsEqualTo(script); await Assert.That(error.ToString()).IsEqualTo(""); + await Assert.That(script).Contains("seq bigint GENERATED ALWAYS AS IDENTITY"); + await Assert.That(script).Contains("(lane, seq)"); await Assert.That(script).Contains("\"a\"\";--{{schema}}\".\"{{outbox}}_outbox\""); var migration = new MigrationBuilder("Npgsql.EntityFrameworkCore.PostgreSQL"); diff --git a/tests/Shared/OutboxOrderedDispatchContractTests.cs b/tests/Shared/OutboxOrderedDispatchContractTests.cs index 11170c093..c3875edbd 100644 --- a/tests/Shared/OutboxOrderedDispatchContractTests.cs +++ b/tests/Shared/OutboxOrderedDispatchContractTests.cs @@ -31,7 +31,7 @@ protected abstract class OrderedWorker : IDisposable public async Task Failed_head_blocks_later_rows_and_retries_preserve_native_payload() { await using var fixture = await CreateFixtureAsync(); - // Insertion order must not replace visible UUID order. + // Each insert commits before the next: database insertion order wins over host UUID order. await fixture.Insert(Id(2), 0); await fixture.Insert(Id(1), 0); await fixture.Insert(Id(3), null); @@ -43,11 +43,11 @@ public async Task Failed_head_blocks_later_rows_and_retries_preserve_native_payl await Assert.That(transport.Ids.Count).IsEqualTo(0); var rows = await fixture.ReadRows(); await Assert.That(rows.Length).IsEqualTo(3); - await Assert.That(rows[0]).IsEqualTo(new Row(Id(1), 1, "broker offline", false, false)); - await Assert.That(rows[1]).IsEqualTo(new Row(Id(2), 0, null, false, false)); + await Assert.That(rows[0]).IsEqualTo(new Row(Id(1), 0, null, false, false)); + await Assert.That(rows[1]).IsEqualTo(new Row(Id(2), 1, "broker offline", false, false)); fail = false; await Assert.That(await worker.DispatchLaneAsync(0)).IsEqualTo(2); - await Assert.That(transport.Ids.SequenceEqual([Id(1), Id(2)])).IsTrue(); + await Assert.That(transport.Ids.SequenceEqual([Id(2), Id(1)])).IsTrue(); await Assert.That(transport.LastBody).IsEquivalentTo(new byte[] { 7, 8, 9 }); await Assert.That(transport.LastKey).IsEqualTo("customer-é"); await Assert.That(transport.LastDeliverAt).IsNull(); diff --git a/website/docs/reference/ordered-dispatch.md b/website/docs/reference/ordered-dispatch.md index 22d13c864..1131fd416 100644 --- a/website/docs/reference/ordered-dispatch.md +++ b/website/docs/reference/ordered-dispatch.md @@ -75,10 +75,10 @@ fenced row outcomes finish. A competing owner cannot take over while that transa even after lease expiry. The worker sets a deadline of half the lease duration for acquiring, reading, sending and committing each batch. It stops admitting rows after one quarter of the lease duration, reserving the remaining deadline for the final admitted send and commit. Slow healthy batches therefore commit a confirmed prefix instead of repeatedly replaying it. A single send must still fit the configured hard deadline. It awaits cancellation completion before freeing borrowed payloads. -Reads follow the partial `(lane, id)` pending index, in PostgreSQL UUID order. Scheduling and existing claims +Reads follow the partial `(lane, seq)` pending index, in database-assigned insertion order. Scheduling and existing claims never cause the worker to skip a head row. A future or live-claimed head temporarily stalls its lane. Later rows with a parked head's ordering key stay parked while other keys can continue, using the parked-key -index. This worker does not itself move poison rows or expose redrive management yet. +index comparing `seq`, so host clock differences cannot let a later same-key row bypass a parked row. This worker does not itself move poison rows or expose redrive management yet. Poison handling, retry limits and key-scoped parking are tracked by [#34](https://github.com/thomhurst/Relayer/issues/34). Messages are sent sequentially through the registered native `ITransport`, preserving original bodies, @@ -93,9 +93,19 @@ successful row still uses one conditional claim UPDATE and one fenced DELETE aro ## Failure boundaries -Ordering means ascending IDs among rows visible to a lane scan, using the broker's own key-ordering semantics. -UUIDv7 IDs do not establish commit order between concurrent business transactions. Applications needing a -business order across concurrent writers must serialize those writes. +Ordering means ascending database-assigned `seq` among rows visible to a lane scan, using the broker's own +key-ordering semantics. UUIDv7 remains the stable message identity, not the ordering cursor. Two strictly +sequential transactions dispatch in commit order even when the later message has a smaller UUID because +application clocks differ. Rows in one transaction receive sequence values in send order, including sends +interleaved across EF contexts sharing that transaction. + +Genuinely concurrent transactions still have no defined order: sequence allocation precedes commit, so a +lower-sequence row may become visible after a higher one has already dispatched. Applications needing a +business order across concurrent writers must serialize those business writes and use idempotent, +version-guarded consumers. Sequence values may have gaps; retain the identity sequence's default cache +of one and never reset it. Upgrade existing tables with the explicit [sequence migration](postgres-schema.md#upgrade-existing-tables-to-insert-sequence-ordering) +before starting upgraded workers. Existing rows retain their former UUID order during that migration; +their historical insertion order cannot be reconstructed. Delivery remains at-least-once. A crash after the broker accepts a message but before database commit replays that identity. Cancellation and database fencing cannot retract a native request already accepted by the diff --git a/website/docs/reference/postgres-schema.md b/website/docs/reference/postgres-schema.md index d1ed1c2d8..73e246b39 100644 --- a/website/docs/reference/postgres-schema.md +++ b/website/docs/reference/postgres-schema.md @@ -54,7 +54,8 @@ and [store registrations](postgres-store.md) must use the same schema and prefix ## Tables and constraints - `relayer_outbox` preserves the original UUID, transport, destination, stable message type, serialized headers - and body, creation time, optional ordering key, lane, delivery time and tenant ID. Attempts default to zero; + and body, creation time, optional ordering key, lane, delivery time and tenant ID. `seq bigint GENERATED ALWAYS AS IDENTITY` + records database insertion order for ordered dispatch; the UUID remains the primary key. Attempts default to zero; `last_error` stores failure details. Status defaults to `pending` and permits `pending` or `parked`. - `relayer_outbox_dead` preserves the message and attempt/error data with a required `failed_at` timestamp. Dead rows live in this table, outside the eligible backlog. @@ -66,8 +67,10 @@ Message IDs and claim tokens cannot be empty UUIDs. A claim token and its expiry present. The [PostgreSQL store](postgres-store.md) enforces conditional, live-token updates; columns and constraints alone do not implement [fencing](outbox-stores.md#claims-and-outcomes). -The outbox has a partial `(lane, ordering_key, id)` index for parked-key barriers, a partial `(lane, id)` index for `status = 'pending'` and a partial `deliver_at` index for non-null -schedules. The inbox has a `processed_at` retention index. Primary keys create their normal unique indexes. +The outbox has a partial `(lane, ordering_key, seq)` index for parked-key barriers, a partial `(lane, seq)` index for `status = 'pending'` and a partial `deliver_at` index for non-null +schedules. The pending sequence index covers ordered rows (`lane IS NOT NULL`); a separate partial `id` index +covers unordered pending rows (`lane IS NULL`) for recovery without changing UUID scan cursors. +The inbox has a `processed_at` retention index. Primary keys create their normal unique indexes. Creation uses `IF NOT EXISTS` for schemas, tables and indexes. Running the script again preserves existing data. It creates missing objects; it does **not** repair incompatible tables or upgrade an older schema. Review existing @@ -98,6 +101,38 @@ no entity mapping, `DbSet`, `EnsureCreated` call or transaction interceptor is r in explicit SQL migration operations. There is no automatic destructive `Down`: choose a retention policy before writing a rollback that drops durable messages. Back up durable data before a schema change. +## Upgrade existing tables to insert-sequence ordering + +Schema creation does not add `seq` to an older table. Stop all application writers and dispatchers before +upgrading, and run the following SQL from an application-owned EF migration or deployment transaction: + +```csharp +migrationBuilder.Sql(PostgreSqlOutboxSchema.CreateInsertSequenceMigrationScript( + new PostgreSqlOutboxOptions { Schema = "messaging", TablePrefix = "orders_" })); +``` + +`CreateInsertSequenceMigrationScript` returns explicit SQL; it never runs a migration automatically. +Use the same schema and prefix as the existing store. Run it once, in one transaction. It locks the outbox, +adds and backfills `seq`, enables a native identity sequence above the backfilled range, and replaces the +pending and parked indexes with `(lane, seq)` and `(lane, ordering_key, seq)`. For example, its default-table +SQL begins with: + +```sql +LOCK TABLE "public"."relayer_outbox" IN ACCESS EXCLUSIVE MODE; +ALTER TABLE "public"."relayer_outbox" ADD COLUMN seq bigint; +WITH numbered AS ( + SELECT id, row_number() OVER (ORDER BY id) AS position FROM "public"."relayer_outbox" +) +UPDATE "public"."relayer_outbox" AS target +SET seq = numbered.position FROM numbered WHERE target.id = numbered.id; +``` + +The complete generated script also sets `NOT NULL`, adds `GENERATED ALWAYS AS IDENTITY`, advances the +sequence, rebuilds both ordered indexes and preserves unordered recovery with a partial UUID index. Existing rows keep their previous UUID order; the database cannot +recover their historical insertion order. New rows follow insertion order independently of host clocks. +Restart only upgraded workers after the migration commits. Keep the identity sequence's default cache +of one and do not reset it. Unordered direct dispatch and maintenance retain their existing UUID cursors. + ## Eligible backlog predicate A provider's count query across all lanes uses an explicit UTC instant: