perf(store-and-forward): rank sweep lanes over a covering narrow index, join payloads for the page only (SF-3, WP6 task 6.3)

The fair-paging sweep computed ROW_NUMBER() over every column of every due
row, so each sweep sorted the whole due backlog with payloads into temp
storage. The ranking now projects only id + lane keys over the new covering
idx_sf_messages_lane (status, category, target, created_at,
last_attempt_at_ms, retry_interval_ms, id), takes the page of ids, and joins
back by primary key. The index is created in place by StoreAndForwardSchema
(idempotent, local only — not part of CDC capture). idx_sf_messages_category
is kept (still used by parked-count filters).

EXPLAIN QUERY PLAN + timing, sqlite3 3.54, 200,000 due rows x ~1 KB payload,
20 targets x 3 categories, LIMIT 500:
  before: SEARCH idx_sf_messages_status_created (status=?) + USE TEMP B-TREE
          FOR ORDER BY (window over full rows) + outer temp b-tree; 1.29 s
  after:  SEARCH USING COVERING INDEX idx_sf_messages_lane (no window sort),
          outer temp b-tree over (id, rank, created_at) only, PK join of 500
          rows; 0.15 s
This commit is contained in:
Joseph Doherty
2026-12-03 09:47:29 -05:00
parent d3c6295670
commit 54416e33bf
4 changed files with 68 additions and 9 deletions
@@ -853,6 +853,31 @@ public class StoreAndForwardStorageTests : IAsyncLifetime, IDisposable
Assert.Equal("a000", dead[0]);
}
/// <summary>
/// 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<string>();
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