diff --git a/docs/requirements/Component-StoreAndForward.md b/docs/requirements/Component-StoreAndForward.md index c26d0938..b16ee540 100644 --- a/docs/requirements/Component-StoreAndForward.md +++ b/docs/requirements/Component-StoreAndForward.md @@ -129,7 +129,7 @@ The telemetry-emitting `ICachedCallLifecycleObserver` hook is dispatched through ### Retry Sweep Indexing -`GetMessagesForRetryAsync` orders candidates `ORDER BY created_at ASC` within the due `status`. The existing `idx_sf_messages_status_due (status, last_attempt_at_ms)` matches the status filter and due-time predicate but not this ordering, forcing a sort/scan on a large sweep. The sweep page is ranked **per `(category, target)` lane** (`ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at)`, ordered by lane rank then `created_at`, limited to `SweepBatchLimit`), so a dead target with hundreds of due rows contributes one row per round like every other lane instead of owning the whole page and starving healthy targets (review 2026-10-21 02/C2); per-target FIFO is preserved. A second covering index, `idx_sf_messages_status_created (status, created_at)`, lets the sweep walk matching rows already in `created_at` order and stop at the batch limit without re-sorting or touching non-pending rows (arch-review WP1.4). Both indexes are retained — `idx_sf_messages_status_due` still backs status+due-time lookups that don't order by `created_at`. +`GetMessagesForRetryAsync` orders candidates `ORDER BY created_at ASC` within the due `status`. The existing `idx_sf_messages_status_due (status, last_attempt_at_ms)` matches the status filter and due-time predicate but not this ordering, forcing a sort/scan on a large sweep. The sweep page is ranked **per `(category, target)` lane** (`ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at)`, ordered by lane rank then `created_at`, limited to `SweepBatchLimit`), so a dead target with hundreds of due rows contributes one row per round like every other lane instead of owning the whole page and starving healthy targets (review 2026-10-21 02/C2); per-target FIFO is preserved. A second covering index, `idx_sf_messages_status_created (status, created_at)`, lets the sweep walk matching rows already in `created_at` order and stop at the batch limit without re-sorting or touching non-pending rows (arch-review WP1.4). Both indexes are retained — `idx_sf_messages_status_due` still backs status+due-time lookups that don't order by `created_at`. **SF-3 (2026-12-03):** the lane ranking runs over a narrow projection (`id` + lane keys) backed by the covering `idx_sf_messages_lane (status, category, target, created_at, last_attempt_at_ms, retry_interval_ms, id)`, so the window needs no sort and never reads a payload; only the chosen page of ids is joined back for full rows (200 000 due 1 KB rows: 1.29 s → 0.15 s per sweep). The index is created in place by `StoreAndForwardSchema.Apply`. ## Parked Message Management diff --git a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardSchema.cs b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardSchema.cs index 8f9ab17b..0a2b47e9 100644 --- a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardSchema.cs +++ b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardSchema.cs @@ -111,6 +111,19 @@ public static class StoreAndForwardSchema "CREATE INDEX IF NOT EXISTS idx_sf_messages_status_created ON sf_messages(status, created_at)"; orderIndex.ExecuteNonQuery(); } + + // SF-3: covering index for the sweep's fair lane ranking. Leading (status, category, + // target, created_at) matches ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY + // created_at) so the window reads rows already in lane order with no sort, and the + // trailing due-predicate columns + id make it covering, so the ranking never reads a + // payload. Applied in place on every boot (idempotent); local only — indexes are not + // part of LocalDb's CDC capture. + using (var laneIndex = connection.CreateCommand()) + { + laneIndex.CommandText = + "CREATE INDEX IF NOT EXISTS idx_sf_messages_lane ON sf_messages(status, category, target, created_at, last_attempt_at_ms, retry_interval_ms, id)"; + laneIndex.ExecuteNonQuery(); + } } /// diff --git a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs index 8b3b008f..da86490c 100644 --- a/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs +++ b/src/ZB.MOM.WW.ScadaBridge.StoreAndForward/StoreAndForwardStorage.cs @@ -211,16 +211,28 @@ public class StoreAndForwardStorage // hundreds of due rows contributes one row per "round" like every other // lane instead of owning the whole page. Within a lane rank order == created_at // order, so per-target FIFO is preserved for the service's GroupBy. + // + // SF-3: the ranking runs over a NARROW projection (id + lane keys) that + // idx_sf_messages_lane covers in (category, target, created_at) order, so the window + // needs no sort and never touches a payload; only the chosen page of ids is joined + // back for the full rows. Ranking over every column used to sort the whole due + // backlog — payloads included — on every sweep. cmd.CommandText = $@" - SELECT {cols} - FROM ( - SELECT {cols}, - ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at ASC) AS lane_rank - FROM sf_messages - WHERE {due} + WITH page AS ( + SELECT id, lane_rank, created_at + FROM ( + SELECT id, created_at, + ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at ASC) AS lane_rank + FROM sf_messages + WHERE {due} + ) + ORDER BY lane_rank ASC, created_at ASC + LIMIT @limit ) - ORDER BY lane_rank ASC, created_at ASC - LIMIT @limit"; + SELECT {SweepColumnsM} + FROM page p + JOIN sf_messages m ON m.id = p.id + ORDER BY p.lane_rank ASC, p.created_at ASC"; cmd.Parameters.AddWithValue("@limit", limit); } else @@ -238,6 +250,15 @@ public class StoreAndForwardStorage return await ReadMessagesAsync(cmd); } + /// The sweep's column list qualified with the m alias (SF-3 join-back). + private static readonly string SweepColumnsM = + string.Join(", ", new[] + { + "id", "category", "target", "payload_json", "retry_count", "max_retries", + "retry_interval_ms", "created_at", "last_attempt_at", "status", "last_error", "origin_instance", + "execution_id", "source_script", "parent_execution_id", + }.Select(c => "m." + c)); + /// /// Updates a message after a delivery attempt. /// diff --git a/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs b/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs index d55c495e..c1d7e2c6 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.StoreAndForward.Tests/StoreAndForwardStorageTests.cs @@ -853,6 +853,31 @@ public class StoreAndForwardStorageTests : IAsyncLifetime, IDisposable Assert.Equal("a000", dead[0]); } + /// + /// SF-3 (WP6 6.3): the sweep ranks lanes over the covering lane index (no payload read, no + /// sort for the window) and joins back only the chosen page by primary key. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task GetMessagesForRetry_RanksOverTheCoveringLaneIndex() + { + await using var connection = _localDb.Db.CreateConnection(); + await using var cmd = connection.CreateCommand(); + cmd.CommandText = @"EXPLAIN QUERY PLAN + SELECT id, created_at, + ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at ASC) AS lane_rank + FROM sf_messages + WHERE status = 0 + AND (last_attempt_at_ms IS NULL OR retry_interval_ms = 0 OR (1 - last_attempt_at_ms) >= retry_interval_ms)"; + var plan = new List(); + await using (var reader = await cmd.ExecuteReaderAsync()) + while (await reader.ReadAsync()) + plan.Add(reader.GetString(3)); + + Assert.Contains(plan, p => p.Contains("COVERING INDEX idx_sf_messages_lane")); + Assert.DoesNotContain(plan, p => p.Contains("TEMP B-TREE")); + } + // ReplaceAll_SwapsTheEntireBuffer_Atomically was DELETED with ReplaceAllAsync in // LocalDb Phase 2, and deliberately not replaced. It asserted a destructive // delete-all-then-insert-all, which was the standby's anti-entropy apply: a resync