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:
@@ -916,7 +916,9 @@ public class StoreAndForwardService
|
||||
// rather than burning a full timeout per remaining message.
|
||||
// Skipped rows keep their RetryCount/LastAttemptAt untouched.
|
||||
var outcome = await RetryMessageAsync(message);
|
||||
if (outcome == RetryOutcome.TransientFailure)
|
||||
if (outcome is RetryOutcome.TransientFailure
|
||||
or RetryOutcome.DeliveredNotRemoved
|
||||
or RetryOutcome.StorageFailure)
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -939,8 +941,47 @@ public class StoreAndForwardService
|
||||
/// short-circuit a <c>(category, target)</c> lane after its first transient
|
||||
/// failure. <see cref="Skipped"/> = no attempt was made (no handler, or the
|
||||
/// 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>
|
||||
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)
|
||||
{
|
||||
@@ -957,19 +998,35 @@ public class StoreAndForwardService
|
||||
var attemptStartUtc = DateTime.UtcNow;
|
||||
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
|
||||
{
|
||||
var success = await handler(message);
|
||||
attemptStopwatch.Stop();
|
||||
if (success)
|
||||
{
|
||||
await _storage.RemoveMessageAsync(message.Id);
|
||||
Interlocked.Decrement(ref _bufferedCount);
|
||||
RaiseActivity("Delivered", message.Category,
|
||||
$"Delivered to {message.Target} after {message.RetryCount} retries");
|
||||
success = await handler(message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
success = false;
|
||||
deliveryFailure = ex;
|
||||
}
|
||||
attemptStopwatch.Stop();
|
||||
|
||||
// Terminal Delivered observer notification — the audit
|
||||
// bridge maps this to Attempted + CachedResolve(Delivered).
|
||||
if (deliveryFailure is null && success)
|
||||
{
|
||||
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(
|
||||
message,
|
||||
CachedCallAttemptOutcome.Delivered,
|
||||
@@ -977,15 +1034,47 @@ public class StoreAndForwardService
|
||||
httpStatus: null,
|
||||
occurredAtUtc: attemptStartUtc,
|
||||
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.
|
||||
message.Status = StoreAndForwardMessageStatus.Parked;
|
||||
message.LastAttemptAt = DateTimeOffset.UtcNow;
|
||||
message.LastError = "Permanent failure (handler returned false)";
|
||||
var parked = await _storage.UpdateMessageIfStatusAsync(
|
||||
message, StoreAndForwardMessageStatus.Pending);
|
||||
bool parked;
|
||||
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)
|
||||
{
|
||||
_logger.LogDebug(
|
||||
@@ -1008,9 +1097,10 @@ public class StoreAndForwardService
|
||||
durationMs: (int)attemptStopwatch.ElapsedMilliseconds);
|
||||
return RetryOutcome.Parked;
|
||||
}
|
||||
catch (Exception ex)
|
||||
|
||||
// The handler threw: a transient delivery failure.
|
||||
{
|
||||
attemptStopwatch.Stop();
|
||||
var ex = deliveryFailure;
|
||||
// Transient failure — increment retry, check max
|
||||
message.RetryCount++;
|
||||
message.LastAttemptAt = DateTimeOffset.UtcNow;
|
||||
|
||||
@@ -187,10 +187,13 @@ public class StoreAndForwardStorage
|
||||
}
|
||||
|
||||
/// <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>
|
||||
/// <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)
|
||||
{
|
||||
await using var connection = OpenConnection();
|
||||
@@ -199,38 +202,41 @@ public class StoreAndForwardStorage
|
||||
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,
|
||||
execution_id, source_script, parent_execution_id";
|
||||
const string due = @"status = @pending
|
||||
AND (last_attempt_at_ms IS NULL
|
||||
const string dueExpr = @"(last_attempt_at_ms IS NULL
|
||||
OR retry_interval_ms = 0
|
||||
OR (@nowMs - last_attempt_at_ms) >= retry_interval_ms)";
|
||||
|
||||
if (limit > 0)
|
||||
{
|
||||
// Page FAIRLY across (category, target) lanes: rank each due row within its
|
||||
// lane (oldest-first) and take the page by rank, so one dead target holding
|
||||
// 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.
|
||||
cmd.CommandText = $@"
|
||||
// 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
|
||||
// (created_at, rowid as the same-instant tie-break), and `blocked_by` counts the
|
||||
// not-yet-due rows at or before each row. Only the lane prefix with
|
||||
// blocked_by = 0 is eligible, so a younger row can never be handed out while an
|
||||
// older row of the same lane is still pending but backing off — previously the
|
||||
// head's failure pushed ITS last_attempt_at forward while the rows behind it
|
||||
// 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}
|
||||
FROM (
|
||||
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
|
||||
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
|
||||
LIMIT @limit";
|
||||
WHERE blocked_by = 0
|
||||
ORDER BY lane_rank ASC, created_at ASC"
|
||||
+ (limit > 0 ? "\n LIMIT @limit" : string.Empty);
|
||||
if (limit > 0)
|
||||
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("@nowMs", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());
|
||||
|
||||
Reference in New Issue
Block a user