Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ To change a decision, add a new entry that supersedes it rather than editing his
| [D75](#d75-failure-diagnostics-are-bounded) | Failure diagnostics are bounded | Accepted |
| [D76](#d76-ef-transaction-coordination-is-independent-of-the-database-provider) | EF transaction coordination is independent of the database provider | Accepted |
| [D77](#d77-batch-items-report-their-own-failures) | Batch items report their own failures | Accepted |
| [D78](#d78-isolate-failed-outbox-batches-using-native-single-sends-and-confirmed-receipts) | Isolate failed outbox batches using native single sends and confirmed receipts | Accepted |

---

Expand Down Expand Up @@ -1866,3 +1867,36 @@ is the source of truth for available combinations.
**Decision.** Delivered `BatchItem<TMessage>` values report failures with `Fail(exception)`. `BatchResult.Success` succeeds unmarked items and `BatchResult.Failure(exception)` fails every delivered item. Opaque item handles contain the original delivery index and a generation of the pooled dispatcher state. Default, manually constructed and expired handles reject failure marking, including while that state serves another invocation. Repeated marking replaces the item's exception; null exceptions are rejected. The index-keyed partial-failure API is removed.

**Consequences.** Item copies preserve delivery association through filtering and reordering without allocating a handle per message. The dispatcher writes into the existing attempt error storage. Deserialization failures, manual settlement precedence, durable settlement and ambiguous buffered sends retain the existing execution and native settlement paths (D11, D28); no native capability is duplicated. Items and contexts remain borrowed for the handler invocation only.

## D78. Isolate failed outbox batches using native single sends and confirmed receipts

**Status:** Accepted. Qualifies D70, D71 and D73's batch-failure handling; durable retry and poison policies remain unchanged.

**Context.** #647 remains possible when a failed batch outcome is assigned to every row. Even D73's
stop after the first single-send `Retry` can indefinitely hold healthy neighbours behind an unclassified
permanent rejection. Native clients already provide all send mechanics: Service Bus 7.21.0
[`SendMessagesAsync`](https://github.com/Azure/azure-sdk-for-net/blob/Azure.Messaging.ServiceBus_7.21.0/sdk/servicebus/Azure.Messaging.ServiceBus/src/Sender/ServiceBusSender.cs)
is atomic per native batch; the adapter can split a supplied group. Dekaf 1.27.0
[`ProduceAllAsync`](https://github.com/thomhurst/Dekaf/blob/v1.27.0/src/Dekaf/Producer/KafkaProducer.cs)
returns metadata on success and throws on aggregate failure. RabbitMQ.Client 7.2.2
[`BasicPublishAsync`](https://github.com/rabbitmq/rabbitmq-dotnet-client/blob/v7.2.2/projects/RabbitMQ.Client/Impl/Channel.cs)
publishes individual messages; Relayer's batch drains those native calls. AWS SQS/SNS 4.1.0 provide
native `Successful` and `Failed` entry lists, already retained by Relayer's batch exceptions
([SQS source](https://github.com/aws/aws-sdk-net/blob/4.1.0.0/sdk/src/Services/SQS/Generated/Model/SendMessageBatchResponse.g.cs),
[SNS source](https://github.com/aws/aws-sdk-net/blob/4.1.0.0/sdk/src/Services/SimpleNotificationService/Generated/Model/PublishBatchResponse.g.cs)).

**Decision.** On failed unordered batches, PostgreSQL, SQL Server and MySQL direct/recovery dispatch
invoke existing native `SendAsync` at most once per unconfirmed row under its original live claim.
Continue after any individual failure; apply each provider's existing classification/backoff policy only
to that row. Cancellation or known claim expiry stops new native sends. Complete successes with the
existing fenced store mutation, never treating a completion error as a send failure. An error-only
`IBatchSendFailure` transport contract exposes confirmed successes without database providers taking
native broker dependencies; SQS/SNS implement it using native response IDs and already completed
chunks/groups. Confirmed successes are completed without another send. This is failure isolation,
not another native retry scheduler or an implementation of broker batching.

**Consequences.** A failed batch costs at most one batch plus `BatchSize` single calls, including an
outage, so one unclassified rejected row cannot repeatedly charge its neighbours. Unknown batch
acceptance can duplicate delivery under at-least-once semantics. Live token fencing protects each
outcome; expired or replaced claims remain recoverable. Successful batches perform the same sends
and completions and allocate no additional memory. Isolation changes only failure-path work.
18 changes: 17 additions & 1 deletion src/Relayer.AmazonSqs/AmazonSnsBatchException.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;
using Relayer.Transports;

namespace Relayer.AmazonSqs;

/// <summary>A native batch accepted some entries but rejected others. Successful entries are not resent.</summary>
public sealed class AmazonSnsBatchException : AmazonSimpleNotificationServiceException
public sealed class AmazonSnsBatchException : AmazonSimpleNotificationServiceException, IBatchSendFailure
{
internal AmazonSnsBatchException(PublishBatchResponse response, int batchOffset)
: base($"SNS PublishBatch rejected {response.Failed.Count} entries. Inspect Response.Failed; earlier entries may already be delivered.")
Expand All @@ -18,4 +19,19 @@ internal AmazonSnsBatchException(PublishBatchResponse response, int batchOffset)
public PublishBatchResponse Response { get; }
/// <summary>The starting index of this native batch within its contiguous destination group.</summary>
public int BatchOffset { get; }
internal int GroupOffset { get; set; }

/// <inheritdoc />
public bool IsConfirmed(int messageIndex)
{
if (messageIndex < 0) return false;
// Earlier native chunks completed before this chunk failed.
if (messageIndex < GroupOffset + BatchOffset) return true;
if (Response.Successful is not { } successful) return false;
foreach (var entry in successful)
if (int.TryParse(entry.Id, System.Globalization.NumberStyles.None,
System.Globalization.CultureInfo.InvariantCulture, out var index) && index == messageIndex - GroupOffset - BatchOffset)
return true;
return false;
}
}
18 changes: 17 additions & 1 deletion src/Relayer.AmazonSqs/AmazonSqsBatchException.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using Amazon.SQS;
using Amazon.SQS.Model;
using Relayer.Transports;

namespace Relayer.AmazonSqs;

/// <summary>A native batch accepted some entries but rejected others. Successful entries are not resent.</summary>
public sealed class AmazonSqsBatchException : AmazonSQSException
public sealed class AmazonSqsBatchException : AmazonSQSException, IBatchSendFailure
{
internal AmazonSqsBatchException(SendMessageBatchResponse response, int batchOffset)
: base($"SQS SendMessageBatch rejected {response.Failed.Count} entries. Inspect Response.Failed; earlier entries may already be delivered.")
Expand All @@ -18,4 +19,19 @@ internal AmazonSqsBatchException(SendMessageBatchResponse response, int batchOff
public SendMessageBatchResponse Response { get; }
/// <summary>The starting index of this native batch within its contiguous destination group.</summary>
public int BatchOffset { get; }
internal int GroupOffset { get; set; }

/// <inheritdoc />
public bool IsConfirmed(int messageIndex)
{
if (messageIndex < 0) return false;
// Earlier native chunks completed before this chunk failed.
if (messageIndex < GroupOffset + BatchOffset) return true;
if (Response.Successful is not { } successful) return false;
foreach (var entry in successful)
if (int.TryParse(entry.Id, System.Globalization.NumberStyles.None,
System.Globalization.CultureInfo.InvariantCulture, out var index) && index == messageIndex - GroupOffset - BatchOffset)
return true;
return false;
}
}
12 changes: 10 additions & 2 deletions src/Relayer.AmazonSqs/SnsSendTransport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,16 @@ public async ValueTask SendBatchAsync(ReadOnlyMemory<OutgoingMessage> messages,
while (end < messages.Length && messages.Span[end].Destination == destination) end++;
var group = messages.Slice(start, end - start);
var tracing = GetEndpoint(destination).Tracing;
if (tracing is null) await SendBatchCoreAsync(group, cancellationToken).ConfigureAwait(false);
else await tracing.SendBatchAsync(group, cancellationToken).ConfigureAwait(false);
try
{
if (tracing is null) await SendBatchCoreAsync(group, cancellationToken).ConfigureAwait(false);
else await tracing.SendBatchAsync(group, cancellationToken).ConfigureAwait(false);
}
catch (AmazonSnsBatchException error)
{
error.GroupOffset = start;
throw;
}
start = end;
}
}
Expand Down
12 changes: 10 additions & 2 deletions src/Relayer.AmazonSqs/SqsSendTransport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,16 @@ public async ValueTask SendBatchAsync(ReadOnlyMemory<OutgoingMessage> messages,
while (end < messages.Length && messages.Span[end].Destination == destination) end++;
var group = messages.Slice(start, end - start);
var tracing = GetEndpoint(destination).Tracing;
if (tracing is null) await SendBatchCoreAsync(group, cancellationToken).ConfigureAwait(false);
else await tracing.SendBatchAsync(group, cancellationToken).ConfigureAwait(false);
try
{
if (tracing is null) await SendBatchCoreAsync(group, cancellationToken).ConfigureAwait(false);
else await tracing.SendBatchAsync(group, cancellationToken).ConfigureAwait(false);
}
catch (AmazonSqsBatchException error)
{
error.GroupOffset = start;
throw;
}
start = end;
}
}
Expand Down
24 changes: 23 additions & 1 deletion src/Relayer.Outbox.MySql/MySqlDirectDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,29 @@ private async ValueTask DispatchAsync(OutboxDispatchBatch batch, CancellationTok
{
try
{
await _store.RecordRetryAsync(_claims[i], error.Message, DateTimeOffset.UtcNow, cancellationToken).ConfigureAwait(false);
var sendError = error;
if (live > 1)
{
var confirmed = error is IBatchSendFailure result && result.IsConfirmed(i);
if (!confirmed)
{
// Never admit another native send after cancellation or known claim expiry.
cancellationToken.ThrowIfCancellationRequested();
if (expires <= DateTimeOffset.UtcNow) continue;
sendError = null;
try { await transport.SendAsync(_messages[i], cancellationToken).ConfigureAwait(false); }
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
catch (Exception failure) { sendError = failure; }
}
if (confirmed || sendError is null)
{
// Completion failures must not be recorded as send failures.
var completed = await _store.CompleteBatchAsync(_claims.AsMemory(i, 1), DateTimeOffset.UtcNow, cancellationToken).ConfigureAwait(false);
_instrumentation?.AddOutboxPending(-completed);
continue;
}
}
await _store.RecordRetryAsync(_claims[i], sendError.Message, DateTimeOffset.UtcNow, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
catch (Exception failure) { DirectDispatchLog.Failed(_logger, failure); }
Expand Down
23 changes: 9 additions & 14 deletions src/Relayer.Outbox.PostgreSql/PostgreSqlDirectDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -241,25 +241,22 @@ private async ValueTask DispatchAsync(OutboxDispatchBatch batch, CancellationTok
catch (Exception error)
{
DirectDispatchLog.Failed(_logger, error);
Exception? retryError = null;
for (var i = 0; i < live; i++)
{
try
{
// Native batches may reject every row because one row is invalid. Retry each
// individually under the same live claim; at-least-once delivery permits duplicates.
if (retryError is not null)
if (error is IBatchSendFailure result && result.IsConfirmed(i))
{
await RecordSendFailureAsync(batch, i, retryError, cancellationToken, propagateDatabaseFailures, FailureAction.Retry).ConfigureAwait(false);
if (await _store.CompleteBatchAsync(_claims.AsMemory(i, 1), DateTimeOffset.UtcNow, cancellationToken).ConfigureAwait(false) == 1)
_instrumentation?.AddOutboxPending(-1);
}
else if (live > 1 && PostgreSqlLocalTransport.Find(transport) is null)
{
if (expires <= DateTimeOffset.UtcNow)
{
// Stop native sends, but still attempt fenced backoff for every remaining
// claim. Expired or replaced ownership remains protected by the store.
retryError = error;
await RecordSendFailureAsync(batch, i, error, cancellationToken, propagateDatabaseFailures, FailureAction.Retry).ConfigureAwait(false);
// Unsent rows retain their claim for recovery; no send outcome is inferred.
continue;
}
Exception? singleError = null;
Expand All @@ -273,8 +270,7 @@ private async ValueTask DispatchAsync(OutboxDispatchBatch batch, CancellationTok
_instrumentation?.AddOutboxPending(-1);
continue;
}
if (await RecordSendFailureAsync(batch, i, singleError, cancellationToken, propagateDatabaseFailures).ConfigureAwait(false) == FailureAction.Retry)
retryError = singleError; // A retryable failure ends this isolation pass.
await RecordSendFailureAsync(batch, i, singleError, cancellationToken, propagateDatabaseFailures).ConfigureAwait(false);
}
else await RecordSendFailureAsync(batch, i, error, cancellationToken, propagateDatabaseFailures,
retryable: PostgreSqlLocalTransport.Find(transport) is null).ConfigureAwait(false);
Expand Down Expand Up @@ -305,20 +301,20 @@ private async ValueTask DispatchAsync(OutboxDispatchBatch batch, CancellationTok
}
}

private async ValueTask<FailureAction> RecordSendFailureAsync(OutboxDispatchBatch batch, int index, Exception error,
CancellationToken cancellationToken, bool propagateDatabaseFailures, FailureAction? knownAction = null, bool retryable = true)
private async ValueTask RecordSendFailureAsync(OutboxDispatchBatch batch, int index, Exception error,
CancellationToken cancellationToken, bool propagateDatabaseFailures, bool retryable = true)
{
BufferedOutboxMessage? row = null;
for (var i = 0; i < batch.Count; i++)
if (batch.Rows[i].Id == _claims[index].MessageId) { row = batch.Rows[i]; break; }
if (row is null) throw new InvalidOperationException("The failed claim has no dispatch row.");
var action = knownAction ?? await _failures.ClassifyAsync(error, row.Id, row.MessageType, row.Attempts + 1,
var action = await _failures.ClassifyAsync(error, row.Id, row.MessageType, row.Attempts + 1,
row.TenantId, _messages[index], cancellationToken).ConfigureAwait(false);
if (action == FailureAction.Discard)
{
var completed = await _store.CompleteBatchAsync(_claims.AsMemory(index, 1), DateTimeOffset.UtcNow, cancellationToken).ConfigureAwait(false);
_instrumentation?.AddOutboxPending(-completed);
return action;
return;
}
if (action is not (FailureAction.Retry or FailureAction.DeadLetter))
throw new InvalidOperationException("The dispatch failure classifier returned an unknown action.");
Expand All @@ -328,7 +324,6 @@ private async ValueTask<FailureAction> RecordSendFailureAsync(OutboxDispatchBatc
if (propagateDatabaseFailures) _recoveredPoison++;
else _instrumentation?.RecordOutboxPoison();
}
return action;
}

// Recovery owns a separate dispatcher instance, so these buffers never overlap the commit queue.
Expand Down
Loading
Loading