fix(sf): per-lane due-ness keeps per-target FIFO; post-delivery storage error is not a delivery failure (SF-1, SF-2, WP3 task 3.5)
This commit is contained in:
@@ -129,7 +129,7 @@ The telemetry-emitting `ICachedCallLifecycleObserver` hook is dispatched through
|
|||||||
|
|
||||||
### Retry Sweep Indexing
|
### 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. **Due-ness is decided per lane, not per row (2026-12-02 review SF-1):** the window runs over every *pending* row of the lane in enqueue order (`created_at`, then `rowid` as the same-instant tie-break) and only the prefix of due rows before the first not-yet-due row is eligible, so a younger row is never delivered while an older row of the same lane is still backing off (previously the failed head's `last_attempt_at` moved forward while the rows behind it kept older stamps, and a later sweep delivered B before A). An older *parked* row does not hold a lane. A dead target is therefore probed once per head retry interval. **A storage error after the handler has answered is not a delivery failure (SF-2):** the try covers the handler only; on success the row delete is retried (3 attempts) and, if it still fails, the row stays `Pending` with `RetryCount`/`LastError` untouched (never parked), the lane stops for that sweep, and the next due sweep re-delivers it (at-least-once; downstream idempotency remains the caller's). A failed park write after a permanent failure is handled the same way. 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`.
|
||||||
|
|
||||||
## Parked Message Management
|
## Parked Message Management
|
||||||
|
|
||||||
|
|||||||
@@ -916,7 +916,9 @@ public class StoreAndForwardService
|
|||||||
// rather than burning a full timeout per remaining message.
|
// rather than burning a full timeout per remaining message.
|
||||||
// Skipped rows keep their RetryCount/LastAttemptAt untouched.
|
// Skipped rows keep their RetryCount/LastAttemptAt untouched.
|
||||||
var outcome = await RetryMessageAsync(message);
|
var outcome = await RetryMessageAsync(message);
|
||||||
if (outcome == RetryOutcome.TransientFailure)
|
if (outcome is RetryOutcome.TransientFailure
|
||||||
|
or RetryOutcome.DeliveredNotRemoved
|
||||||
|
or RetryOutcome.StorageFailure)
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -939,8 +941,47 @@ public class StoreAndForwardService
|
|||||||
/// short-circuit a <c>(category, target)</c> lane after its first transient
|
/// short-circuit a <c>(category, target)</c> lane after its first transient
|
||||||
/// failure. <see cref="Skipped"/> = no attempt was made (no handler, or the
|
/// failure. <see cref="Skipped"/> = no attempt was made (no handler, or the
|
||||||
/// row's status changed under a concurrent apply); its RetryCount is untouched.
|
/// row's status changed under a concurrent apply); its RetryCount is untouched.
|
||||||
|
/// <see cref="DeliveredNotRemoved"/> = the handler succeeded but the buffer row could
|
||||||
|
/// not be deleted (SF-2); <see cref="StorageFailure"/> = the handler answered but the
|
||||||
|
/// resulting status write failed. Both leave the row Pending with its counters
|
||||||
|
/// untouched and stop the lane for this sweep, like a transient failure.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
internal enum RetryOutcome { Delivered, Parked, TransientFailure, Skipped }
|
internal enum RetryOutcome { Delivered, Parked, TransientFailure, Skipped, DeliveredNotRemoved, StorageFailure }
|
||||||
|
|
||||||
|
/// <summary>Attempts the post-delivery delete; how many times before giving up.</summary>
|
||||||
|
internal const int DeliveredRemoveAttempts = 3;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Deletes a delivered message's buffer row, retrying a transient storage error (e.g.
|
||||||
|
/// <c>SQLITE_BUSY</c> on the shared LocalDb file) a few times. Returns false — after
|
||||||
|
/// logging an error — when every attempt failed; never throws.
|
||||||
|
/// </summary>
|
||||||
|
private async Task<bool> TryRemoveDeliveredMessageAsync(StoreAndForwardMessage message)
|
||||||
|
{
|
||||||
|
for (var attempt = 1; ; attempt++)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _storage.RemoveMessageAsync(message.Id);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (attempt < DeliveredRemoveAttempts)
|
||||||
|
{
|
||||||
|
_logger.LogWarning(ex,
|
||||||
|
"Delivered message {MessageId} could not be removed from the buffer (attempt {Attempt}/{Max}); retrying",
|
||||||
|
message.Id, attempt, DeliveredRemoveAttempts);
|
||||||
|
await Task.Delay(TimeSpan.FromMilliseconds(50 * attempt));
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex,
|
||||||
|
"Message {MessageId} was DELIVERED to {Target} but could not be removed from the buffer after {Max} attempts; " +
|
||||||
|
"it stays pending and will be delivered again on the next due sweep",
|
||||||
|
message.Id, message.Target, DeliveredRemoveAttempts);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private async Task<RetryOutcome> RetryMessageAsync(StoreAndForwardMessage message)
|
private async Task<RetryOutcome> RetryMessageAsync(StoreAndForwardMessage message)
|
||||||
{
|
{
|
||||||
@@ -957,19 +998,35 @@ public class StoreAndForwardService
|
|||||||
var attemptStartUtc = DateTime.UtcNow;
|
var attemptStartUtc = DateTime.UtcNow;
|
||||||
var attemptStopwatch = System.Diagnostics.Stopwatch.StartNew();
|
var attemptStopwatch = System.Diagnostics.Stopwatch.StartNew();
|
||||||
|
|
||||||
|
// SF-2: the try covers the delivery attempt ONLY. Bookkeeping after the handler
|
||||||
|
// has answered (the row delete on success, the park on a permanent failure) is a
|
||||||
|
// storage operation, not a delivery outcome — a SQLITE_BUSY / disk-full there used
|
||||||
|
// to land in the transient catch below, which counted a retry against a call that
|
||||||
|
// had SUCCEEDED and could park it (an operator Retry then re-sent it).
|
||||||
|
bool success;
|
||||||
|
Exception? deliveryFailure = null;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var success = await handler(message);
|
success = await handler(message);
|
||||||
attemptStopwatch.Stop();
|
}
|
||||||
if (success)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
await _storage.RemoveMessageAsync(message.Id);
|
success = false;
|
||||||
Interlocked.Decrement(ref _bufferedCount);
|
deliveryFailure = ex;
|
||||||
RaiseActivity("Delivered", message.Category,
|
}
|
||||||
$"Delivered to {message.Target} after {message.RetryCount} retries");
|
attemptStopwatch.Stop();
|
||||||
|
|
||||||
// Terminal Delivered observer notification — the audit
|
if (deliveryFailure is null && success)
|
||||||
// bridge maps this to Attempted + CachedResolve(Delivered).
|
{
|
||||||
|
if (!await TryRemoveDeliveredMessageAsync(message))
|
||||||
|
{
|
||||||
|
// Delivered, but the row is still Pending in the buffer, so the next due
|
||||||
|
// sweep will deliver it again (downstream idempotency is the caller's
|
||||||
|
// responsibility). RetryCount is NOT incremented and the row is NOT parked.
|
||||||
|
// The lane stops here so the rows behind it are not delivered ahead of the
|
||||||
|
// (re-)delivery of this one — per-target FIFO holds even for the duplicate.
|
||||||
|
RaiseActivity("Delivered", message.Category,
|
||||||
|
$"Delivered to {message.Target} after {message.RetryCount} retries (buffer delete failed; will re-deliver)");
|
||||||
await PostObserverNotification(
|
await PostObserverNotification(
|
||||||
message,
|
message,
|
||||||
CachedCallAttemptOutcome.Delivered,
|
CachedCallAttemptOutcome.Delivered,
|
||||||
@@ -977,15 +1034,47 @@ public class StoreAndForwardService
|
|||||||
httpStatus: null,
|
httpStatus: null,
|
||||||
occurredAtUtc: attemptStartUtc,
|
occurredAtUtc: attemptStartUtc,
|
||||||
durationMs: (int)attemptStopwatch.ElapsedMilliseconds);
|
durationMs: (int)attemptStopwatch.ElapsedMilliseconds);
|
||||||
return RetryOutcome.Delivered;
|
return RetryOutcome.DeliveredNotRemoved;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Interlocked.Decrement(ref _bufferedCount);
|
||||||
|
RaiseActivity("Delivered", message.Category,
|
||||||
|
$"Delivered to {message.Target} after {message.RetryCount} retries");
|
||||||
|
|
||||||
|
// Terminal Delivered observer notification — the audit
|
||||||
|
// bridge maps this to Attempted + CachedResolve(Delivered).
|
||||||
|
await PostObserverNotification(
|
||||||
|
message,
|
||||||
|
CachedCallAttemptOutcome.Delivered,
|
||||||
|
lastError: null,
|
||||||
|
httpStatus: null,
|
||||||
|
occurredAtUtc: attemptStartUtc,
|
||||||
|
durationMs: (int)attemptStopwatch.ElapsedMilliseconds);
|
||||||
|
return RetryOutcome.Delivered;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (deliveryFailure is null)
|
||||||
|
{
|
||||||
// Permanent failure on retry — park immediately.
|
// Permanent failure on retry — park immediately.
|
||||||
message.Status = StoreAndForwardMessageStatus.Parked;
|
message.Status = StoreAndForwardMessageStatus.Parked;
|
||||||
message.LastAttemptAt = DateTimeOffset.UtcNow;
|
message.LastAttemptAt = DateTimeOffset.UtcNow;
|
||||||
message.LastError = "Permanent failure (handler returned false)";
|
message.LastError = "Permanent failure (handler returned false)";
|
||||||
var parked = await _storage.UpdateMessageIfStatusAsync(
|
bool parked;
|
||||||
message, StoreAndForwardMessageStatus.Pending);
|
try
|
||||||
|
{
|
||||||
|
parked = await _storage.UpdateMessageIfStatusAsync(
|
||||||
|
message, StoreAndForwardMessageStatus.Pending);
|
||||||
|
}
|
||||||
|
catch (Exception storageEx)
|
||||||
|
{
|
||||||
|
// A storage failure writing the park is not a delivery failure: leave the
|
||||||
|
// row Pending with its counters untouched; the next due sweep re-attempts
|
||||||
|
// it (and parks it then). Stop the lane, as for any unresolved head.
|
||||||
|
_logger.LogError(storageEx,
|
||||||
|
"Message {MessageId} to {Target} failed permanently but the park could not be written; it stays pending",
|
||||||
|
message.Id, message.Target);
|
||||||
|
return RetryOutcome.StorageFailure;
|
||||||
|
}
|
||||||
if (!parked)
|
if (!parked)
|
||||||
{
|
{
|
||||||
_logger.LogDebug(
|
_logger.LogDebug(
|
||||||
@@ -1008,9 +1097,10 @@ public class StoreAndForwardService
|
|||||||
durationMs: (int)attemptStopwatch.ElapsedMilliseconds);
|
durationMs: (int)attemptStopwatch.ElapsedMilliseconds);
|
||||||
return RetryOutcome.Parked;
|
return RetryOutcome.Parked;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
|
||||||
|
// The handler threw: a transient delivery failure.
|
||||||
{
|
{
|
||||||
attemptStopwatch.Stop();
|
var ex = deliveryFailure;
|
||||||
// Transient failure — increment retry, check max
|
// Transient failure — increment retry, check max
|
||||||
message.RetryCount++;
|
message.RetryCount++;
|
||||||
message.LastAttemptAt = DateTimeOffset.UtcNow;
|
message.LastAttemptAt = DateTimeOffset.UtcNow;
|
||||||
|
|||||||
@@ -187,10 +187,13 @@ public class StoreAndForwardStorage
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets all messages that are due for retry (Pending status, last attempt older than retry interval).
|
/// Gets the messages that are due for retry (Pending status, last attempt older than retry
|
||||||
|
/// interval), restricted per <c>(category, target)</c> lane to the due rows that are not
|
||||||
|
/// preceded by an older still-pending, not-yet-due row of the same lane — a lane never
|
||||||
|
/// passes its own backing-off head (SF-1).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="limit">Maximum number of messages to return, or 0 for no limit.</param>
|
/// <param name="limit">Maximum number of messages to return, or 0 for no limit.</param>
|
||||||
/// <returns>A task that resolves to the list of messages due for retry, ordered by creation time ascending.</returns>
|
/// <returns>A task that resolves to the eligible messages, ordered by lane rank then creation time (enqueue order within each lane).</returns>
|
||||||
public async Task<List<StoreAndForwardMessage>> GetMessagesForRetryAsync(int limit = 0)
|
public async Task<List<StoreAndForwardMessage>> GetMessagesForRetryAsync(int limit = 0)
|
||||||
{
|
{
|
||||||
await using var connection = OpenConnection();
|
await using var connection = OpenConnection();
|
||||||
@@ -199,38 +202,41 @@ public class StoreAndForwardStorage
|
|||||||
const string cols = @"id, category, target, payload_json, retry_count, max_retries,
|
const string cols = @"id, category, target, payload_json, retry_count, max_retries,
|
||||||
retry_interval_ms, created_at, last_attempt_at, status, last_error, origin_instance,
|
retry_interval_ms, created_at, last_attempt_at, status, last_error, origin_instance,
|
||||||
execution_id, source_script, parent_execution_id";
|
execution_id, source_script, parent_execution_id";
|
||||||
const string due = @"status = @pending
|
const string dueExpr = @"(last_attempt_at_ms IS NULL
|
||||||
AND (last_attempt_at_ms IS NULL
|
|
||||||
OR retry_interval_ms = 0
|
OR retry_interval_ms = 0
|
||||||
OR (@nowMs - last_attempt_at_ms) >= retry_interval_ms)";
|
OR (@nowMs - last_attempt_at_ms) >= retry_interval_ms)";
|
||||||
|
|
||||||
if (limit > 0)
|
// Per-target FIFO (SF-1). Due-ness is decided PER LANE, not per row: the window
|
||||||
{
|
// runs over EVERY pending row of a (category, target) lane in enqueue order
|
||||||
// Page FAIRLY across (category, target) lanes: rank each due row within its
|
// (created_at, rowid as the same-instant tie-break), and `blocked_by` counts the
|
||||||
// lane (oldest-first) and take the page by rank, so one dead target holding
|
// not-yet-due rows at or before each row. Only the lane prefix with
|
||||||
// hundreds of due rows contributes one row per "round" like every other
|
// blocked_by = 0 is eligible, so a younger row can never be handed out while an
|
||||||
// lane instead of owning the whole page. Within a lane rank order == created_at
|
// older row of the same lane is still pending but backing off — previously the
|
||||||
// order, so per-target FIFO is preserved for the service's GroupBy.
|
// head's failure pushed ITS last_attempt_at forward while the rows behind it
|
||||||
cmd.CommandText = $@"
|
// kept their older stamps, so a later sweep delivered B before A. It also means
|
||||||
|
// a dead target is probed once per head retry interval rather than by whichever
|
||||||
|
// staggered row happened to come due on each sweep.
|
||||||
|
//
|
||||||
|
// The page is then taken FAIRLY across lanes by lane rank (review 2026-10-21
|
||||||
|
// 02/C2): one dead target holding hundreds of rows contributes one row per
|
||||||
|
// "round" like every other lane instead of owning the whole page. Within a lane
|
||||||
|
// rank order == enqueue order, preserved by the service's stable GroupBy.
|
||||||
|
cmd.CommandText = $@"
|
||||||
SELECT {cols}
|
SELECT {cols}
|
||||||
FROM (
|
FROM (
|
||||||
SELECT {cols},
|
SELECT {cols},
|
||||||
ROW_NUMBER() OVER (PARTITION BY category, target ORDER BY created_at ASC) AS lane_rank
|
ROW_NUMBER() OVER lane AS lane_rank,
|
||||||
|
SUM(CASE WHEN {dueExpr} THEN 0 ELSE 1 END) OVER lane AS blocked_by
|
||||||
FROM sf_messages
|
FROM sf_messages
|
||||||
WHERE {due}
|
WHERE status = @pending
|
||||||
|
WINDOW lane AS (PARTITION BY category, target ORDER BY created_at ASC, rowid ASC
|
||||||
|
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
|
||||||
)
|
)
|
||||||
ORDER BY lane_rank ASC, created_at ASC
|
WHERE blocked_by = 0
|
||||||
LIMIT @limit";
|
ORDER BY lane_rank ASC, created_at ASC"
|
||||||
|
+ (limit > 0 ? "\n LIMIT @limit" : string.Empty);
|
||||||
|
if (limit > 0)
|
||||||
cmd.Parameters.AddWithValue("@limit", limit);
|
cmd.Parameters.AddWithValue("@limit", limit);
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
cmd.CommandText = $@"
|
|
||||||
SELECT {cols}
|
|
||||||
FROM sf_messages
|
|
||||||
WHERE {due}
|
|
||||||
ORDER BY created_at ASC";
|
|
||||||
}
|
|
||||||
|
|
||||||
cmd.Parameters.AddWithValue("@pending", (int)StoreAndForwardMessageStatus.Pending);
|
cmd.Parameters.AddWithValue("@pending", (int)StoreAndForwardMessageStatus.Pending);
|
||||||
cmd.Parameters.AddWithValue("@nowMs", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
|
cmd.Parameters.AddWithValue("@nowMs", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
|
||||||
|
|||||||
@@ -842,6 +842,105 @@ public class StoreAndForwardServiceTests : IAsyncLifetime, IDisposable
|
|||||||
Assert.Equal(1, maxConcurrent); // one (category,target) lane: strictly sequential
|
Assert.Equal(1, maxConcurrent); // one (category,target) lane: strictly sequential
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── SF-1: per-target FIFO across sweeps ──
|
||||||
|
|
||||||
|
private async Task ExecSqlAsync(string sql)
|
||||||
|
{
|
||||||
|
await using var conn = _localDb.Db.CreateConnection();
|
||||||
|
await using var cmd = conn.CreateCommand();
|
||||||
|
cmd.CommandText = sql;
|
||||||
|
await cmd.ExecuteNonQueryAsync();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Back-dates a buffered row's last attempt so it is due on the next sweep.</summary>
|
||||||
|
private Task MakeDueAsync(string id) => ExecSqlAsync(
|
||||||
|
$"UPDATE sf_messages SET last_attempt_at_ms = {DateTimeOffset.UtcNow.AddMinutes(-5).ToUnixTimeMilliseconds()} WHERE id = '{id}'");
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// SF-1 (the review's exact scenario): A then B to one target. The head A fails, so its
|
||||||
|
/// last attempt moves to now while B keeps its older stamp. On the next sweep B is due and
|
||||||
|
/// A is not — pre-fix B was delivered first and A's later delivery overwrote B's newer
|
||||||
|
/// value. The lane must wait for its head.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task RetrySweep_YoungerRow_NeverPassesBackingOffHead()
|
||||||
|
{
|
||||||
|
var delivered = new List<string>();
|
||||||
|
var targetUp = false;
|
||||||
|
_service.RegisterDeliveryHandler(StoreAndForwardCategory.CachedDbWrite, msg =>
|
||||||
|
{
|
||||||
|
if (!targetUp) throw new TimeoutException("Mes down");
|
||||||
|
delivered.Add(msg.Id);
|
||||||
|
return Task.FromResult(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
await _service.EnqueueAsync(StoreAndForwardCategory.CachedDbWrite, "Mes", "{}",
|
||||||
|
attemptImmediateDelivery: false, retryInterval: TimeSpan.FromSeconds(30), messageId: "A");
|
||||||
|
await _service.EnqueueAsync(StoreAndForwardCategory.CachedDbWrite, "Mes", "{}",
|
||||||
|
attemptImmediateDelivery: false, retryInterval: TimeSpan.FromSeconds(30), messageId: "B");
|
||||||
|
await MakeDueAsync("A");
|
||||||
|
await MakeDueAsync("B");
|
||||||
|
|
||||||
|
// Sweep 1: A is attempted and fails (its last attempt is now "now"); B is skipped.
|
||||||
|
await _service.RetryPendingMessagesAsync();
|
||||||
|
Assert.Empty(delivered);
|
||||||
|
|
||||||
|
// The target recovers. B is still due by its own stamp, A is not.
|
||||||
|
targetUp = true;
|
||||||
|
await _service.RetryPendingMessagesAsync();
|
||||||
|
Assert.Empty(delivered); // pre-fix: ["B"]
|
||||||
|
|
||||||
|
// Once the head is due, the lane drains in enqueue order.
|
||||||
|
await MakeDueAsync("A");
|
||||||
|
await _service.RetryPendingMessagesAsync();
|
||||||
|
Assert.Equal(new[] { "A", "B" }, delivered);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── SF-2: storage failure after a successful delivery ──
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// SF-2: the handler succeeded but the row delete fails. The delivery must not be counted
|
||||||
|
/// as a failed retry (pre-fix: RetryCount++ and, on the last allowed retry, Parked — an
|
||||||
|
/// operator Retry then re-sent a call that had succeeded). The row stays Pending with its
|
||||||
|
/// counters untouched, and the lane stops so the younger row is not delivered ahead of
|
||||||
|
/// the head's re-delivery.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task RetrySweep_DeleteFailsAfterDelivery_IsNotCountedAsFailure()
|
||||||
|
{
|
||||||
|
var delivered = new List<string>();
|
||||||
|
_service.RegisterDeliveryHandler(StoreAndForwardCategory.ExternalSystem, msg =>
|
||||||
|
{
|
||||||
|
delivered.Add(msg.Id);
|
||||||
|
return Task.FromResult(true);
|
||||||
|
});
|
||||||
|
await _service.EnqueueAsync(StoreAndForwardCategory.ExternalSystem, "api", "{}",
|
||||||
|
attemptImmediateDelivery: false, retryInterval: TimeSpan.Zero, maxRetries: 1, messageId: "head");
|
||||||
|
await _service.EnqueueAsync(StoreAndForwardCategory.ExternalSystem, "api", "{}",
|
||||||
|
attemptImmediateDelivery: false, retryInterval: TimeSpan.Zero, maxRetries: 1, messageId: "next");
|
||||||
|
|
||||||
|
await ExecSqlAsync(
|
||||||
|
"CREATE TRIGGER fail_delete BEFORE DELETE ON sf_messages BEGIN SELECT RAISE(ABORT, 'disk I/O error'); END;");
|
||||||
|
|
||||||
|
await _service.RetryPendingMessagesAsync();
|
||||||
|
|
||||||
|
Assert.Equal(new[] { "head" }, delivered); // lane stopped after the head
|
||||||
|
var head = await _service.GetMessageByIdAsync("head");
|
||||||
|
Assert.NotNull(head);
|
||||||
|
Assert.Equal(StoreAndForwardMessageStatus.Pending, head!.Status); // pre-fix: Parked
|
||||||
|
Assert.Equal(0, head.RetryCount); // pre-fix: 1
|
||||||
|
Assert.Null(head.LastError);
|
||||||
|
|
||||||
|
// Storage recovers: the head is re-delivered (at-least-once) and the lane drains in order.
|
||||||
|
await ExecSqlAsync("DROP TRIGGER fail_delete;");
|
||||||
|
await _service.RetryPendingMessagesAsync();
|
||||||
|
Assert.Equal(new[] { "head", "head", "next" }, delivered);
|
||||||
|
Assert.Null(await _service.GetMessageByIdAsync("head"));
|
||||||
|
Assert.Null(await _service.GetMessageByIdAsync("next"));
|
||||||
|
}
|
||||||
|
|
||||||
private static void InterlockedMax(ref int target, int value)
|
private static void InterlockedMax(ref int target, int value)
|
||||||
{
|
{
|
||||||
int current;
|
int current;
|
||||||
|
|||||||
@@ -135,18 +135,23 @@ public class StoreAndForwardStorageTests : IAsyncLifetime, IDisposable
|
|||||||
{
|
{
|
||||||
// Exercise the julianday elapsed-time comparison with a
|
// Exercise the julianday elapsed-time comparison with a
|
||||||
// non-zero retry interval. A message attempted just now must NOT be due; one
|
// non-zero retry interval. A message attempted just now must NOT be due; one
|
||||||
// attempted long ago must be due.
|
// attempted long ago must be due. Each row is its own (category, target) lane:
|
||||||
|
// within ONE lane a not-due older row would hold back the rows behind it (SF-1,
|
||||||
|
// covered by GetMessagesForRetry_RowBehindNotDueHead_IsNotReturned).
|
||||||
var notDue = CreateMessage("notdue", StoreAndForwardCategory.ExternalSystem);
|
var notDue = CreateMessage("notdue", StoreAndForwardCategory.ExternalSystem);
|
||||||
|
notDue.Target = "lane-notdue";
|
||||||
notDue.RetryIntervalMs = (long)TimeSpan.FromHours(1).TotalMilliseconds;
|
notDue.RetryIntervalMs = (long)TimeSpan.FromHours(1).TotalMilliseconds;
|
||||||
notDue.LastAttemptAt = DateTimeOffset.UtcNow;
|
notDue.LastAttemptAt = DateTimeOffset.UtcNow;
|
||||||
await _storage.EnqueueAsync(notDue);
|
await _storage.EnqueueAsync(notDue);
|
||||||
|
|
||||||
var due = CreateMessage("due", StoreAndForwardCategory.ExternalSystem);
|
var due = CreateMessage("due", StoreAndForwardCategory.ExternalSystem);
|
||||||
|
due.Target = "lane-due";
|
||||||
due.RetryIntervalMs = (long)TimeSpan.FromMinutes(5).TotalMilliseconds;
|
due.RetryIntervalMs = (long)TimeSpan.FromMinutes(5).TotalMilliseconds;
|
||||||
due.LastAttemptAt = DateTimeOffset.UtcNow.AddHours(-2);
|
due.LastAttemptAt = DateTimeOffset.UtcNow.AddHours(-2);
|
||||||
await _storage.EnqueueAsync(due);
|
await _storage.EnqueueAsync(due);
|
||||||
|
|
||||||
var neverAttempted = CreateMessage("never", StoreAndForwardCategory.ExternalSystem);
|
var neverAttempted = CreateMessage("never", StoreAndForwardCategory.ExternalSystem);
|
||||||
|
neverAttempted.Target = "lane-never";
|
||||||
neverAttempted.RetryIntervalMs = (long)TimeSpan.FromHours(1).TotalMilliseconds;
|
neverAttempted.RetryIntervalMs = (long)TimeSpan.FromHours(1).TotalMilliseconds;
|
||||||
neverAttempted.LastAttemptAt = null;
|
neverAttempted.LastAttemptAt = null;
|
||||||
await _storage.EnqueueAsync(neverAttempted);
|
await _storage.EnqueueAsync(neverAttempted);
|
||||||
@@ -853,6 +858,60 @@ public class StoreAndForwardStorageTests : IAsyncLifetime, IDisposable
|
|||||||
Assert.Equal("a000", dead[0]);
|
Assert.Equal("a000", dead[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// SF-1: due-ness is per lane. A younger row whose own stamp is due must not be returned
|
||||||
|
/// while an older pending row of the SAME lane is still backing off; another lane is
|
||||||
|
/// unaffected.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task GetMessagesForRetry_RowBehindNotDueHead_IsNotReturned()
|
||||||
|
{
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
var head = NewMsg("head", StoreAndForwardMessageStatus.Pending, now.AddMinutes(-10));
|
||||||
|
head.LastAttemptAt = now; // just failed: not due for 30 s
|
||||||
|
var behind = NewMsg("behind", StoreAndForwardMessageStatus.Pending, now.AddMinutes(-9));
|
||||||
|
behind.LastAttemptAt = now.AddMinutes(-5); // due by its own stamp
|
||||||
|
var other = NewMsg("other", StoreAndForwardMessageStatus.Pending, now.AddMinutes(-8));
|
||||||
|
other.Target = "other-target";
|
||||||
|
other.LastAttemptAt = now.AddMinutes(-5);
|
||||||
|
await _storage.EnqueueAsync(head);
|
||||||
|
await _storage.EnqueueAsync(behind);
|
||||||
|
await _storage.EnqueueAsync(other);
|
||||||
|
|
||||||
|
foreach (var limit in new[] { 0, 500 })
|
||||||
|
{
|
||||||
|
var ids = (await _storage.GetMessagesForRetryAsync(limit)).Select(m => m.Id).ToList();
|
||||||
|
Assert.Equal(new[] { "other" }, ids); // pre-fix: behind, other
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// SF-1: an older PARKED row does not block its lane (only pending rows hold a lane), and
|
||||||
|
/// a due head releases the rows behind it in enqueue order.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[Fact]
|
||||||
|
public async Task GetMessagesForRetry_ParkedOlderRow_DoesNotBlockLane()
|
||||||
|
{
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
var parked = NewMsg("parked", StoreAndForwardMessageStatus.Parked, now.AddMinutes(-10));
|
||||||
|
parked.LastAttemptAt = now;
|
||||||
|
var a = NewMsg("a", StoreAndForwardMessageStatus.Pending, now.AddMinutes(-9));
|
||||||
|
a.LastAttemptAt = now.AddMinutes(-5);
|
||||||
|
var b = NewMsg("b", StoreAndForwardMessageStatus.Pending, now.AddMinutes(-8));
|
||||||
|
b.LastAttemptAt = now.AddMinutes(-5);
|
||||||
|
var c = NewMsg("c", StoreAndForwardMessageStatus.Pending, now.AddMinutes(-7));
|
||||||
|
c.LastAttemptAt = now; // not due: blocks nothing older, holds itself back
|
||||||
|
await _storage.EnqueueAsync(parked);
|
||||||
|
await _storage.EnqueueAsync(a);
|
||||||
|
await _storage.EnqueueAsync(b);
|
||||||
|
await _storage.EnqueueAsync(c);
|
||||||
|
|
||||||
|
var ids = (await _storage.GetMessagesForRetryAsync(500)).Select(m => m.Id).ToList();
|
||||||
|
Assert.Equal(new[] { "a", "b" }, ids);
|
||||||
|
}
|
||||||
|
|
||||||
// ReplaceAll_SwapsTheEntireBuffer_Atomically was DELETED with ReplaceAllAsync in
|
// ReplaceAll_SwapsTheEntireBuffer_Atomically was DELETED with ReplaceAllAsync in
|
||||||
// LocalDb Phase 2, and deliberately not replaced. It asserted a destructive
|
// 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
|
// delete-all-then-insert-all, which was the standby's anti-entropy apply: a resync
|
||||||
|
|||||||
Reference in New Issue
Block a user