diff --git a/docs/decisions.md b/docs/decisions.md index bb554273d..55723dfdb 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -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 | --- @@ -1866,3 +1867,36 @@ is the source of truth for available combinations. **Decision.** Delivered `BatchItem` 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. diff --git a/src/Relayer.AmazonSqs/AmazonSnsBatchException.cs b/src/Relayer.AmazonSqs/AmazonSnsBatchException.cs index eb15fc501..f4dd7c2ac 100644 --- a/src/Relayer.AmazonSqs/AmazonSnsBatchException.cs +++ b/src/Relayer.AmazonSqs/AmazonSnsBatchException.cs @@ -1,10 +1,11 @@ using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; +using Relayer.Transports; namespace Relayer.AmazonSqs; /// A native batch accepted some entries but rejected others. Successful entries are not resent. -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.") @@ -18,4 +19,19 @@ internal AmazonSnsBatchException(PublishBatchResponse response, int batchOffset) public PublishBatchResponse Response { get; } /// The starting index of this native batch within its contiguous destination group. public int BatchOffset { get; } + internal int GroupOffset { get; set; } + + /// + 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; + } } diff --git a/src/Relayer.AmazonSqs/AmazonSqsBatchException.cs b/src/Relayer.AmazonSqs/AmazonSqsBatchException.cs index 52a84d256..56140bda3 100644 --- a/src/Relayer.AmazonSqs/AmazonSqsBatchException.cs +++ b/src/Relayer.AmazonSqs/AmazonSqsBatchException.cs @@ -1,10 +1,11 @@ using Amazon.SQS; using Amazon.SQS.Model; +using Relayer.Transports; namespace Relayer.AmazonSqs; /// A native batch accepted some entries but rejected others. Successful entries are not resent. -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.") @@ -18,4 +19,19 @@ internal AmazonSqsBatchException(SendMessageBatchResponse response, int batchOff public SendMessageBatchResponse Response { get; } /// The starting index of this native batch within its contiguous destination group. public int BatchOffset { get; } + internal int GroupOffset { get; set; } + + /// + 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; + } } diff --git a/src/Relayer.AmazonSqs/SnsSendTransport.cs b/src/Relayer.AmazonSqs/SnsSendTransport.cs index 5b1381a30..eafdcb969 100644 --- a/src/Relayer.AmazonSqs/SnsSendTransport.cs +++ b/src/Relayer.AmazonSqs/SnsSendTransport.cs @@ -115,8 +115,16 @@ public async ValueTask SendBatchAsync(ReadOnlyMemory 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; } } diff --git a/src/Relayer.AmazonSqs/SqsSendTransport.cs b/src/Relayer.AmazonSqs/SqsSendTransport.cs index ef17e13d7..25d081ba6 100644 --- a/src/Relayer.AmazonSqs/SqsSendTransport.cs +++ b/src/Relayer.AmazonSqs/SqsSendTransport.cs @@ -204,8 +204,16 @@ public async ValueTask SendBatchAsync(ReadOnlyMemory 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; } } diff --git a/src/Relayer.Outbox.MySql/MySqlDirectDispatcher.cs b/src/Relayer.Outbox.MySql/MySqlDirectDispatcher.cs index ff2088108..c1405fbfb 100644 --- a/src/Relayer.Outbox.MySql/MySqlDirectDispatcher.cs +++ b/src/Relayer.Outbox.MySql/MySqlDirectDispatcher.cs @@ -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); } diff --git a/src/Relayer.Outbox.PostgreSql/PostgreSqlDirectDispatcher.cs b/src/Relayer.Outbox.PostgreSql/PostgreSqlDirectDispatcher.cs index 5d8486bda..83d6756cf 100644 --- a/src/Relayer.Outbox.PostgreSql/PostgreSqlDirectDispatcher.cs +++ b/src/Relayer.Outbox.PostgreSql/PostgreSqlDirectDispatcher.cs @@ -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; @@ -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); @@ -305,20 +301,20 @@ private async ValueTask DispatchAsync(OutboxDispatchBatch batch, CancellationTok } } - private async ValueTask 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."); @@ -328,7 +324,6 @@ private async ValueTask RecordSendFailureAsync(OutboxDispatchBatc if (propagateDatabaseFailures) _recoveredPoison++; else _instrumentation?.RecordOutboxPoison(); } - return action; } // Recovery owns a separate dispatcher instance, so these buffers never overlap the commit queue. diff --git a/src/Relayer.Outbox.SqlServer/SqlServerDirectDispatcher.cs b/src/Relayer.Outbox.SqlServer/SqlServerDirectDispatcher.cs index f389359e6..faf530fd1 100644 --- a/src/Relayer.Outbox.SqlServer/SqlServerDirectDispatcher.cs +++ b/src/Relayer.Outbox.SqlServer/SqlServerDirectDispatcher.cs @@ -202,15 +202,37 @@ private async ValueTask DispatchAsync(OutboxDispatchBatch batch, CancellationTok catch (Exception error) { DirectDispatchLog.Failed(_logger, error); - var retryable = SqlServerSendFailure.IsRetryable(_retrySendFailure, error, _logger); for (var i = 0; i < live; i++) { try { - if (retryable) - 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); + if (recordInvalid) _recoveredCompletions += completed; + else _instrumentation?.AddOutboxPending(-completed); + continue; + } + } + if (SqlServerSendFailure.IsRetryable(_retrySendFailure, sendError, _logger)) + await _store.RecordRetryAsync(_claims[i], sendError.Message, DateTimeOffset.UtcNow, cancellationToken).ConfigureAwait(false); else - await _store.RecordFailureAsync(_claims[i], error.Message, DateTimeOffset.UtcNow, cancellationToken).ConfigureAwait(false); + await _store.RecordFailureAsync(_claims[i], sendError.Message, DateTimeOffset.UtcNow, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } catch (Exception failure) { DirectDispatchLog.Failed(_logger, failure); } diff --git a/src/Relayer/Transports/IBatchSendFailure.cs b/src/Relayer/Transports/IBatchSendFailure.cs new file mode 100644 index 000000000..b06662fc8 --- /dev/null +++ b/src/Relayer/Transports/IBatchSendFailure.cs @@ -0,0 +1,10 @@ +namespace Relayer.Transports; + +/// Exposes confirmed native successes when a batch send throws. +/// Implemented by transport exceptions. Unconfirmed messages may have been delivered; +/// retrying them preserves at-least-once semantics and can duplicate delivery. +public interface IBatchSendFailure +{ + /// Whether the native client confirmed delivery of the zero-based message in the supplied batch. + bool IsConfirmed(int messageIndex); +} diff --git a/src/Relayer/Transports/ITransport.cs b/src/Relayer/Transports/ITransport.cs index 741d5153c..029326267 100644 --- a/src/Relayer/Transports/ITransport.cs +++ b/src/Relayer/Transports/ITransport.cs @@ -31,6 +31,7 @@ public interface ITransport : IAsyncDisposable /// Observe cancellation. Apply each message's native callbacks before sending. The batch memory and each message's /// borrowed storage remain valid until completion and must not be retained afterward. Completion does not imply /// atomicity: a native batch failure or cancellation can leave some messages delivered. + /// Exceptions can implement to expose confirmed native successes. /// ValueTask SendBatchAsync(ReadOnlyMemory messages, CancellationToken cancellationToken); diff --git a/tests/Relayer.Outbox.MySql.Tests/SharedDirectDispatchContractTests.cs b/tests/Relayer.Outbox.MySql.Tests/SharedDirectDispatchContractTests.cs index cfc142b6f..b365c36f9 100644 --- a/tests/Relayer.Outbox.MySql.Tests/SharedDirectDispatchContractTests.cs +++ b/tests/Relayer.Outbox.MySql.Tests/SharedDirectDispatchContractTests.cs @@ -235,6 +235,20 @@ private static Guid ReadId(MySqlDataReader reader) return new(bytes, bigEndian: true); } + public override async ValueTask RecoverAsync(OutboxRecord[] records, CancellationToken cancellationToken = default) + { + var rows = new List(); + foreach (var record in records) + { + var row = new BufferedOutboxMessage(); + row.Copy(record, 1); + rows.Add(row); + } + var batch = new OutboxDispatchBatch(); + batch.Take(rows, rows.Count, DateTimeOffset.UtcNow); + await _worker!.DispatchRecoveredAsync(batch, cancellationToken); + } + public override async Task StopAsync() { if (_worker is null) return; diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/DispatchBackoffTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/DispatchBackoffTests.cs index 19cc39ebc..972ae3936 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/DispatchBackoffTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/DispatchBackoffTests.cs @@ -203,7 +203,7 @@ public async Task Failed_native_batch_isolates_rejected_row_and_completes_health } [Test] - public async Task Batch_outage_stops_isolation_after_first_retry_and_backs_off_every_row() + public async Task Batch_outage_bounds_isolation_to_one_single_send_per_row_and_backs_off_every_row() { await using var fixture = new PostgreSqlFixture(); await fixture.StartAsync(); @@ -222,7 +222,7 @@ public async Task Batch_outage_stops_isolation_after_first_retry_and_backs_off_e NullLogger.Instance); var before = DateTimeOffset.UtcNow; await worker.DispatchRecoveredAsync(rows.AsMemory(0, count), default); - await Assert.That(transport.Attempts).IsEqualTo(2); // One batch and one single native send. + await Assert.That(transport.Attempts).IsEqualTo(5); // One batch and at most one single native send per row. await using var state = source.CreateCommand("SELECT count(*), bool_and(attempts = 1 AND status = 'pending' AND deliver_at >= @before + interval '1 second' AND claim_token IS NULL), (SELECT count(*) FROM relayer_outbox_dead) FROM relayer_outbox"); state.Parameters.AddWithValue("before", before); await using var reader = await state.ExecuteReaderAsync(); diff --git a/tests/Relayer.Outbox.PostgreSql.Tests/SharedDirectDispatchContractTests.cs b/tests/Relayer.Outbox.PostgreSql.Tests/SharedDirectDispatchContractTests.cs index f47f873c4..216f7e9a9 100644 --- a/tests/Relayer.Outbox.PostgreSql.Tests/SharedDirectDispatchContractTests.cs +++ b/tests/Relayer.Outbox.PostgreSql.Tests/SharedDirectDispatchContractTests.cs @@ -10,8 +10,6 @@ namespace Relayer.Outbox.PostgreSql.Tests; [InheritsTests] public sealed class SharedDirectDispatchContractTests : OutboxDirectDispatchContractTests { - protected override bool IsolatesFailedNativeBatches => true; - protected override async Task CreateFixtureAsync(RecordingTransport transport, int batchSize = 100, int queueCapacity = 256) { @@ -53,6 +51,8 @@ public override async Task ReadRowsAsync() return rows.ToArray(); } + public override ValueTask RecoverAsync(OutboxRecord[] records, CancellationToken cancellationToken = default) => _worker!.DispatchRecoveredAsync(records, cancellationToken); + public override async Task StopAsync() { if (_worker is null) return; diff --git a/tests/Relayer.Outbox.SqlServer.Tests/SharedDirectDispatchContractTests.cs b/tests/Relayer.Outbox.SqlServer.Tests/SharedDirectDispatchContractTests.cs index 1972c7021..33488d0a7 100644 --- a/tests/Relayer.Outbox.SqlServer.Tests/SharedDirectDispatchContractTests.cs +++ b/tests/Relayer.Outbox.SqlServer.Tests/SharedDirectDispatchContractTests.cs @@ -264,6 +264,20 @@ public override async Task ReadRowsAsync() return rows.ToArray(); } + public override async ValueTask RecoverAsync(OutboxRecord[] records, CancellationToken cancellationToken = default) + { + var rows = new List(); + foreach (var record in records) + { + var row = new SqlServerBufferedMessage(); + row.Copy(record, 1, unordered: true); + rows.Add(row); + } + var batch = new OutboxDispatchBatch(); + batch.Take(rows, rows.Count, DateTimeOffset.UtcNow); + await _worker!.DispatchRecoveredAsync(batch, cancellationToken); + } + public override async Task StopAsync() { if (_worker is null) return; diff --git a/tests/Relayer.Tests/ServiceBusSendEmulatorTests.cs b/tests/Relayer.Tests/ServiceBusSendEmulatorTests.cs index d15ac45a1..e7959336b 100644 --- a/tests/Relayer.Tests/ServiceBusSendEmulatorTests.cs +++ b/tests/Relayer.Tests/ServiceBusSendEmulatorTests.cs @@ -12,6 +12,43 @@ namespace Relayer.Tests; public class ServiceBusSendEmulatorTests { + [Test] + public async Task Rejected_native_batch_can_isolate_oversized_row_from_valid_neighbour() + { + var stack = await SharedBrokers.ServiceBus.Value; + using var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(2)); + var token = timeout.Token; + await using var client = new ServiceBusClient(stack.Emulator.GetConnectionString(), new ServiceBusClientOptions + { + RetryOptions = new ServiceBusRetryOptions { MaxRetries = 0 } + }); + var admin = new ServiceBusAdministrationClient(stack.Emulator.GetHttpConnectionString()); + var queue = TestContext.Current!.Isolation.GetIsolatedName("batch-isolation"); + var options = new ServiceBusTransportOptions { Client = client, AdministrationClient = admin }; + options.Queues.Add(new(queue) { DefaultMessageTimeToLive = TimeSpan.FromHours(1), MaxSizeInMegabytes = 100, + DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(10) }); + await using var transport = new ServiceBusSendTransport("isolation", client, false, options, + [queue], TopologyMode.Provision, admin); + try + { + var report = await transport.ApplyTopologyAsync(TopologyMode.Provision, token); + await Assert.That(report.Differences.Count).IsEqualTo(0); + // The rejected row leads the batch, so the healthy neighbour was never admitted. + var rejected = new OutgoingMessage(queue, new byte[2 * 1024 * 1024]); + var healthy = new OutgoingMessage(queue, new byte[] { 42 }); + await Assert.That(async () => await transport.SendBatchAsync(new[] { rejected, healthy }, token)) + .Throws(); + await Assert.That(async () => await transport.SendAsync(rejected, token)).Throws(); + await transport.SendAsync(healthy, token); + await using var receiver = client.CreateReceiver(queue); + var delivered = await receiver.ReceiveMessageAsync(TimeSpan.FromSeconds(30), token); + await Assert.That(delivered).IsNotNull(); + await Assert.That(delivered!.Body.ToArray()).IsEquivalentTo(new byte[] { 42 }); + await receiver.CompleteMessageAsync(delivered, token); + } + finally { await admin.DeleteQueueAsync(queue, token); } + } + [Test] public async Task Native_sends_batches_sessions_scheduling_and_topology_round_trip() { diff --git a/tests/Relayer.Tests/SnsSendTests.cs b/tests/Relayer.Tests/SnsSendTests.cs index 1d71415e6..8dc494020 100644 --- a/tests/Relayer.Tests/SnsSendTests.cs +++ b/tests/Relayer.Tests/SnsSendTests.cs @@ -12,6 +12,25 @@ namespace Relayer.Tests; public class SnsSendTests { + [Test] + public async Task Native_receipts_index_completed_groups_and_chunks_in_the_original_batch() + { + using var client = new SnsTestClient { FailBatch = true, FailBatchOnCall = 3 }; + await using var transport = new SnsSendTransport("sns", client, false, Options(client)); + await transport.StartAsync(default); + OutgoingMessage[] messages = [new("ordered.fifo", "{}"u8.ToArray(), orderingKey: new WireString("key")), + .. Enumerable.Repeat(new OutgoingMessage("orders", "{}"u8.ToArray()), 12)]; + AmazonSnsBatchException? failure = null; + try { await transport.SendBatchAsync(messages, default); } + catch (AmazonSnsBatchException error) { failure = error; } + await Assert.That(failure).IsNotNull(); + await Assert.That(failure!.BatchOffset).IsEqualTo(10); + for (var index = 0; index < 12; index++) + await Assert.That(((IBatchSendFailure)failure).IsConfirmed(index)).IsTrue(); + await Assert.That(((IBatchSendFailure)failure).IsConfirmed(12)).IsFalse(); + await Assert.That(((IBatchSendFailure)failure).IsConfirmed(13)).IsFalse(); + } + [Test] public async Task Hosted_sender_uses_native_topics_and_generated_envelope_without_owning_client() { @@ -123,6 +142,10 @@ public async Task Batches_split_native_limits_once_per_callback_and_preserve_par await Assert.That(failure!.Response.Successful.Single().Id).IsEqualTo("0"); await Assert.That(failure.Response.Failed.Single().Id).IsEqualTo("1"); await Assert.That(failure.BatchOffset).IsEqualTo(0); + await Assert.That(((IBatchSendFailure)failure).IsConfirmed(0)).IsTrue(); + await Assert.That(((IBatchSendFailure)failure).IsConfirmed(1)).IsFalse(); + await Assert.That(((IBatchSendFailure)failure).IsConfirmed(-1)).IsFalse(); + await Assert.That(((IBatchSendFailure)failure).IsConfirmed(100)).IsFalse(); await Assert.That(client.Batches.Count).IsEqualTo(5); await transport.SendAsync(new("orders", "{}"u8.ToArray()), default); await Assert.That(client.Sent.Single().Attributes.Count).IsEqualTo(0); @@ -361,6 +384,7 @@ internal sealed record SnsSent(string Arn, string Body, string? Group, string? D internal readonly List Subscribes = []; internal readonly Dictionary SubscriptionAttributes = new() { ["RawMessageDelivery"] = "true" }; internal bool FailBatch; + internal int FailBatchOnCall; internal bool Missing; internal bool Paginate; internal int Lookups; @@ -383,7 +407,7 @@ public override async Task PublishBatchAsync(PublishBatchR MessageDeduplicationId = entry.MessageDeduplicationId, Subject = entry.Subject, MessageAttributes = entry.MessageAttributes, }))).ToArray()); if (Gate is not null) await Gate.Task.WaitAsync(cancellationToken); - return new() { Successful = [new() { Id = "0" }], Failed = FailBatch ? [new() { Id = "1", Code = "InvalidParameter", SenderFault = true }] : [], ResponseMetadata = new() { RequestId = "batch-request" } }; + return new() { Successful = [new() { Id = "0" }], Failed = FailBatch && (FailBatchOnCall == 0 || Batches.Count == FailBatchOnCall) ? [new() { Id = "1", Code = "InvalidParameter", SenderFault = true }] : [], ResponseMetadata = new() { RequestId = "batch-request" } }; } public override Task ListTopicsAsync(ListTopicsRequest request, CancellationToken cancellationToken = default) { diff --git a/tests/Relayer.Tests/SqsSendTests.cs b/tests/Relayer.Tests/SqsSendTests.cs index 5dd0ee5a6..cd5100b77 100644 --- a/tests/Relayer.Tests/SqsSendTests.cs +++ b/tests/Relayer.Tests/SqsSendTests.cs @@ -13,6 +13,25 @@ namespace Relayer.Tests; public class SqsSendTests { + [Test] + public async Task Native_receipts_index_completed_groups_and_chunks_in_the_original_batch() + { + using var client = new SqsTestClient { FailBatch = true, FailBatchOnCall = 3 }; + await using var transport = Transport(client); + await transport.StartAsync(default); + OutgoingMessage[] messages = [new("ordered.fifo", "{}"u8.ToArray(), orderingKey: new WireString("key")), + .. Enumerable.Repeat(new OutgoingMessage("orders", "{}"u8.ToArray()), 12)]; + AmazonSqsBatchException? failure = null; + try { await transport.SendBatchAsync(messages, default); } + catch (AmazonSqsBatchException error) { failure = error; } + await Assert.That(failure).IsNotNull(); + await Assert.That(failure!.BatchOffset).IsEqualTo(10); + for (var index = 0; index < 12; index++) + await Assert.That(((IBatchSendFailure)failure).IsConfirmed(index)).IsTrue(); + await Assert.That(((IBatchSendFailure)failure).IsConfirmed(12)).IsFalse(); + await Assert.That(((IBatchSendFailure)failure).IsConfirmed(13)).IsFalse(); + } + [Test] public async Task Hosted_sender_serializes_the_real_generated_envelope() { @@ -247,6 +266,10 @@ public async Task Partial_batch_failure_exposes_native_response_and_does_not_ret await Assert.That(failure!.Response.Failed.Single().Id).IsEqualTo("1"); await Assert.That(failure.Response.Successful.Single().Id).IsEqualTo("0"); await Assert.That(failure.BatchOffset).IsEqualTo(0); + await Assert.That(((IBatchSendFailure)failure).IsConfirmed(0)).IsTrue(); + await Assert.That(((IBatchSendFailure)failure).IsConfirmed(1)).IsFalse(); + await Assert.That(((IBatchSendFailure)failure).IsConfirmed(-1)).IsFalse(); + await Assert.That(((IBatchSendFailure)failure).IsConfirmed(100)).IsFalse(); await Assert.That(client.Batches.Count).IsEqualTo(1); await transport.SendAsync(new("orders", "{}"u8.ToArray()), default); await Assert.That(client.Sent.Single().Attributes.Count).IsEqualTo(0); @@ -493,6 +516,7 @@ internal sealed record SqsSent(string Url, string Body, string? Group, string? D internal readonly List Creates = []; internal readonly Dictionary NativeAttributes = new() { ["MaximumMessageSize"] = "1048576", ["FifoQueue"] = "true", ["ContentBasedDeduplication"] = "true" }; internal bool FailBatch; + internal int FailBatchOnCall; internal bool Missing; internal int Lookups; internal int Disposals; @@ -517,7 +541,7 @@ public override async Task SendMessageBatchAsync(SendM return new SendMessageBatchResponse { Successful = [new() { Id = "0" }], - Failed = FailBatch ? [new() { Id = "1", Code = "InvalidMessageContents", SenderFault = true }] : [], + Failed = FailBatch && (FailBatchOnCall == 0 || Batches.Count == FailBatchOnCall) ? [new() { Id = "1", Code = "InvalidMessageContents", SenderFault = true }] : [], ResponseMetadata = new() { RequestId = "batch-request" }, }; } diff --git a/tests/Shared/OutboxDirectDispatchContractTests.cs b/tests/Shared/OutboxDirectDispatchContractTests.cs index bedd26c36..0adec1cd0 100644 --- a/tests/Shared/OutboxDirectDispatchContractTests.cs +++ b/tests/Shared/OutboxDirectDispatchContractTests.cs @@ -5,7 +5,7 @@ namespace Relayer.TestFixtures; public abstract class OutboxDirectDispatchContractTests { - protected virtual bool IsolatesFailedNativeBatches => false; + protected abstract Task CreateFixtureAsync(RecordingTransport transport, int batchSize = 100, int queueCapacity = 256); @@ -16,6 +16,7 @@ protected abstract class DispatchFixture : IAsyncDisposable public abstract Task ReadRowsAsync(); // Drain committed work before returning. Tests release blocked native sends first. public abstract Task StopAsync(); + public abstract ValueTask RecoverAsync(OutboxRecord[] records, CancellationToken cancellationToken = default); public abstract ValueTask DisposeAsync(); public async Task CommitAsync(params OutboxRecord[] records) @@ -162,23 +163,54 @@ public async Task Partial_native_batch_failure_preserves_or_completes_every_row_ await transport.Entered.Task.WaitAsync(TimeSpan.FromSeconds(30)); await fixture.CommitAsync(Record(3)); await fixture.StopAsync(); - if (IsolatesFailedNativeBatches) - { - // The failed batch accepted one row before throwing. Single-send isolation - // completes both rows, duplicating the accepted row under at-least-once delivery. - await Assert.That(transport.Calls.Select(call => call.Count)).IsEquivalentTo(new[] { 2, 1, 1, 1 }); - await Assert.That(transport.Received.Select(sent => sent.Body[0])).IsEquivalentTo(new byte[] { 1, 1, 2, 3 }); - await Assert.That((await fixture.ReadRowsAsync()).Length).IsEqualTo(0); - return; - } + // Unknown acceptance is retried individually; duplicate delivery is allowed. + await Assert.That(transport.Calls.Select(call => call.Count)).IsEquivalentTo(new[] { 2, 1, 1, 1 }); + await Assert.That(transport.Received.Select(sent => sent.Body[0])).IsEquivalentTo(new byte[] { 1, 1, 2, 3 }); + await Assert.That((await fixture.ReadRowsAsync()).Length).IsEqualTo(0); + } + + [Test] + [Arguments(false, false, false)] + [Arguments(false, true, false)] + [Arguments(true, false, false)] + [Arguments(true, true, false)] + [Arguments(false, false, true)] + [Arguments(true, false, true)] + public async Task Rejected_row_does_not_charge_healthy_neighbours(bool recovery, bool confirmed, bool rejectedFirst) + { + var transport = new RecordingTransport { RejectValue = rejectedFirst ? (byte)1 : (byte)2, ConfirmPartial = confirmed }; + await using var fixture = await CreateFixtureAsync(transport); + // Recovery exercises the same store dispatcher after losing the commit notification. + if (recovery) await fixture.StopAsync(); + var first = Record(1); + var second = Record(2); + var rejected = rejectedFirst ? first : second; + await fixture.CommitAsync(first, second); + if (recovery) await fixture.RecoverAsync([first, second]); + else await fixture.StopAsync(); + await Assert.That(transport.Received.Select(sent => sent.Body[0])).IsEquivalentTo(new byte[] { rejectedFirst ? (byte)2 : (byte)1 }); + await Assert.That(transport.Calls.Select(call => call.Count)).IsEquivalentTo(confirmed ? new[] { 2, 1 } : new[] { 2, 1, 1 }); + await Assert.That(await fixture.ReadRowsAsync()).IsEquivalentTo(new[] + { new Row(rejected.Id, 1, "native send rejected", false, false) }); + } + + [Test] + public async Task Cancellation_during_single_send_stops_isolation_without_charging_other_rows() + { + using var cancellation = new CancellationTokenSource(); + var transport = new RecordingTransport { PartialFirst = 1, CancelAfterSingle = cancellation }; + await using var fixture = await CreateFixtureAsync(transport); + await fixture.StopAsync(); + var first = Record(1); + var second = Record(2); + await fixture.CommitAsync(first, second); + await Assert.That(async () => await fixture.RecoverAsync([first, second], cancellation.Token)) + .Throws(); await Assert.That(transport.Calls.Select(call => call.Count)).IsEquivalentTo(new[] { 2, 1 }); - await Assert.That(transport.Received.Count).IsEqualTo(2); - await Assert.That(transport.Received.Count(sent => sent.Body[0] == 3)).IsEqualTo(1); - await Assert.That(transport.Received.Count(sent => sent.Body[0] is 1 or 2)).IsEqualTo(1); await Assert.That(await fixture.ReadRowsAsync()).IsEquivalentTo(new[] { - new Row(first.Id, 1, "native send failed", false, false), - new Row(second.Id, 1, "native send failed", false, false) + new Row(first.Id, 0, null, true, true), + new Row(second.Id, 0, null, true, true) }); } @@ -218,7 +250,10 @@ public sealed record NativeCall(string Destination, int Count); public sealed class RecordingTransport : ITransport { public bool Block { get; init; } + public CancellationTokenSource? CancelAfterSingle { get; init; } public string? CapabilityFailure { get; init; } + public byte? RejectValue { get; init; } + public bool ConfirmPartial { get; init; } public int FailFirst; public int PartialFirst; public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); @@ -244,7 +279,9 @@ public async ValueTask SendAsync(OutgoingMessage message, CancellationToken canc Entered.TrySetResult(); if (Block) await Release.Task.WaitAsync(cancellationToken); if (Interlocked.Exchange(ref FailFirst, 0) != 0) throw new InvalidOperationException("native send failed"); + if (message.Body.Span[0] == RejectValue) throw new InvalidOperationException("native send rejected"); Record(message); + CancelAfterSingle?.Cancel(); } public async ValueTask SendBatchAsync(ReadOnlyMemory messages, CancellationToken cancellationToken) @@ -252,6 +289,11 @@ public async ValueTask SendBatchAsync(ReadOnlyMemory messages, Calls.Enqueue(new(messages.Span[0].Destination, messages.Length)); Entered.TrySetResult(); if (Block) await Release.Task.WaitAsync(cancellationToken); + if (RejectValue.HasValue) + { + if (ConfirmPartial) Record(messages.Span[0]); + throw ConfirmPartial ? new PartialFailure() : new InvalidOperationException("native batch rejected"); + } if (Interlocked.Exchange(ref PartialFirst, 0) != 0) { Record(messages.Span[0]); @@ -261,6 +303,11 @@ public async ValueTask SendBatchAsync(ReadOnlyMemory messages, for (var i = 0; i < messages.Length; i++) Record(messages.Span[i]); } + private sealed class PartialFailure : Exception, IBatchSendFailure + { + public bool IsConfirmed(int messageIndex) => messageIndex == 0; + } + private void Record(OutgoingMessage message) { // Due scheduling is handled by the outbox, not this native endpoint. diff --git a/website/docs/reference/mysql-store.md b/website/docs/reference/mysql-store.md index 542758492..2d6c66f91 100644 --- a/website/docs/reference/mysql-store.md +++ b/website/docs/reference/mysql-store.md @@ -374,8 +374,12 @@ This includes invalid transport destinations and malformed-row quarantine. Retri rolled-back transitions do not change these counters. All native send exceptions are retried indefinitely, including a permanent broker rejection, because -native batch errors do not supply a portable per-row permanent classification. A failed native batch -applies backoff to every claimed row in that batch; partial acceptance can duplicate delivery on retry. +the store has no portable per-row permanent classification. After a batch fails, direct and recovery +dispatch try each unconfirmed row once with native `SendAsync` while its original claim remains live. +Confirmed native successes (including SQS/SNS response entries) complete without being resent. Only +failed single sends receive durable backoff; healthy neighbours complete independently. There are at +most `BatchSize` single sends per failed batch. Cancellation stops isolation and no new send starts +after known claim expiry. Uncertain acceptance can duplicate delivery, consistent with at-least-once semantics. Inspect persistent errors and repair routing, payloads or broker configuration through application-owned SQL. `MaxDispatchAttempts` governs explicit `RecordFailureAsync` calls and preparation failures, including prior diagnostic send attempts: a preparation error after a long outage may exhaust that diff --git a/website/docs/reference/postgres-store.md b/website/docs/reference/postgres-store.md index dc40f38a1..80c87182b 100644 --- a/website/docs/reference/postgres-store.md +++ b/website/docs/reference/postgres-store.md @@ -150,11 +150,12 @@ automatic attempt or age ceiling for `Retry`. Configure permanent rules for your monitor pending rows. A retrying ordered head blocks later rows with its key until it succeeds or is classified permanent. -After a native batch fails, dispatch tries each row once through native `SendAsync` while its claim +Confirmed native batch successes (including SQS/SNS response entries) complete without another send. +After a native batch fails, dispatch tries each unconfirmed row once through native `SendAsync` while its claim remains live, then completes or classifies that row independently. This prevents one rejected row from repeatedly backing off healthy neighbours. A partially successful batch can produce duplicate sends during isolation, consistent with at-least-once delivery. Cancellation stops isolation; expired -claims remain for recovery. Successful batches retain the existing batch send and completion path. The first single-send `Retry` stops isolation and applies fenced durable backoff to the remaining claims with the same error. An outage therefore costs at most one failed batch send and one failed single send per pass; `DeadLetter` and `Discard` allow isolation to continue. Expired or replaced claims cannot be updated and remain eligible for recovery under the existing fencing rules. +claims remain for recovery. Successful batches retain the existing batch send and completion path. Each unconfirmed row receives at most one single send per failed batch, bounded by `BatchSize`; only that row’s single-send failure is classified. A `Retry` no longer assigns its outcome to remaining rows. Expired or replaced claims cannot be updated and remain eligible for recovery under the existing fencing rules. Local-handler failures classified as `Retry`, ordered preparation errors (missing transport, key or ordering capability) and explicit low-level `RecordFailureAsync` calls retain the positive `MaxDispatchAttempts` budget (default **10**). diff --git a/website/docs/reference/sqlserver-store.md b/website/docs/reference/sqlserver-store.md index 84956c0fd..fa60b188d 100644 --- a/website/docs/reference/sqlserver-store.md +++ b/website/docs/reference/sqlserver-store.md @@ -199,7 +199,7 @@ row available for later recovery, even if the broker accepted the message; deliv Explicitly retryable native send failures record the error, increment a diagnostic attempt count (saturating at 30), and release live claims with a durable `deliver_at` deadline. Retry delays start at one second, double after each failed send and stop growing at five minutes. Native clients still own retries within each send; -the dispatcher adds no in-process send retry loop. A completion failure after a successful send retains +native batch failure isolation is described below. A completion failure after a successful send retains the claim without incrementing send attempts. **This worker does not poll or recover rows.** Ordered rows, future schedules, overflow and commits @@ -280,7 +280,12 @@ Only true opts into indefinite durable retries, with one-second exponential dela minutes. Classified sends remain eligible beyond `MaxDispatchAttempts`, including after worker replacement. Null (the default) or false preserves bounded poison handling for permanently rejected or unclassified sends. Use native exception information; do not classify permanent rejections as retryable. -A failed native batch applies the same classification to all its claims because delivery may be partial. +After a batch fails, direct and recovery dispatch try each unconfirmed row once with native +`SendAsync` under its original live claim. Confirmed native successes (including SQS/SNS response +entries) complete without another send. Only a failed single send is classified against that row; +healthy neighbours complete independently. At most `BatchSize` single sends follow a failed batch. +Cancellation stops isolation, and no new send starts after known claim expiry. Native acceptance can +be uncertain, so isolation can duplicate delivery under at-least-once semantics. Explicit low-level `RecordFailureAsync` calls retain the poison transition. Completion errors after broker success do not consume send attempts. diff --git a/website/docs/transports/authoring.md b/website/docs/transports/authoring.md index ed9057c31..30a51dcbe 100644 --- a/website/docs/transports/authoring.md +++ b/website/docs/transports/authoring.md @@ -23,7 +23,7 @@ The core's public surface is classified explicitly below (generic arities are om | --- | --- | | `Relayer` | Application contracts, fluent configuration, middleware, failure policy, requests, tenancy and telemetry configuration: `AsyncApiOptions`, `Batch`, `BatchItem`, `BatchResult`, `ConsumeBuilderExtensions`, `ConsumeDelegate`, `ConsumerBuilder`, `ConsumerCircuitOptions`, `DeadLetterMessage`, `DeadLetterPage`, `DeadLetterSource`, `FailureAction`, `FailureClassifierBuilder`, `FailureHeaders`, `FailureOptions`, `GenerateMessageTypesAttribute`, `IActivityEnricher`, `IBatchHandler`, `IConsumeMiddleware`, `IConsumeTransactionMiddleware`, `IConsumerBuilder`, `IDeadLetterManager`, `IFailureClassifier`, `IHandler`, `IHandlerMarker`, `IRelayerBuilder`, `IRequestClient`, `ISendMiddleware`, `ISender`, `ISettlementFeature`, `ITopology`, `IUpcaster`, `JsonSerializerBuilderExtensions`, `MessageAttribute`, `MessageContext`, `MessageDeserializationException`, `MessageEnvelopeException`, `MessageEnvelopeMode`, `MessageFeatures`, `MessageHeaders`, `MessageType`, `OutboxTenantBinding`, `RelayerServiceCollectionExtensions`, `RelayerTelemetry`, `ReplyExtensions`, `RequestOptions`, `RouteBuilder`, `SendBuilderExtensions`, `SendContext`, `SendDelegate`, `SendOptions`, `SendRouteOptions`, `SendTransactionRequirement`, `TenantContext`, `TenantServiceCollectionExtensions`, `Tombstone`, `TopologyMode`, `TopologyReport`, `TracingBuilderExtensions`, `TracingOptions`, `TransportBuilder`, `TransportSerializerExtensions`, `UnknownMessageTypeException`, `WireString`. | | `Relayer.Pipeline` | Generated registration and receive/failure composition: `BatchHandlerDescriptor`, `BatchReceiveDelegate`, `BatchReceiveExecutor`, `ConsumeFailureDelegate`, `ConsumeMessage`, `ConsumePipeline`, `ConsumePipelineBuilder`, `ConsumerInfrastructureExtensions`, `ConsumerPipelineExtensions`, `DefaultFailureClassifier`, `DefaultMessageContext`, `FailurePipeline`, `HandlerDescriptor`, `HandlerRegistry`, `IConsumerInfrastructure`, `MessageTypeRegistry`, `ReceivePipeline`, `TombstoneHandlerDescriptor`, `UpcasterRegistry`. | -| `Relayer.Transports` | Native bindings, envelope I/O, scheduling, adapter telemetry, configuration definitions and persistence integration: `ConsumerDefinition`, `ConsumptionModel`, `DeadLetterInfo`, `Disposition`, `DispositionKind`, `EndpointTelemetry`, `EndpointTelemetryOptions`, `FailureMessageCopyDelegate`, `HeaderNames`, `IConsumerDefinition`, `IFailureScheduler`, `IMessageBinding`, `IMessageHeaderReader`, `IMessageHeaderWriter`, `IOutboxEnlistment`, `IOutboxStore`, `IPartitionMessageBinding`, `IPartitionSource`, `IRelayerInfrastructure`, `IRouteDefinition`, `ITransport`, `ITransportCapabilityInitializer`, `ITransportSendTracing`, `MessageCreationContext`, `MessageEnvelope`, `MessageEnvelopeMetadata`, `MessageHeaders`, `MessageOperationTracing`, `MessageTraceData`, `MessageTracing`, `MessagingEndpoint`, `MessagingOperation`, `NativeMessage`, `NativeSendOptionsExtensions`, `OutboxClaim`, `OutboxHeaders`, `OutboxReadRequest`, `OutboxRecord`, `OutgoingMessage`, `PartitionAssignmentToken`, `PartitionCompletionToken`, `PartitionCompletionWindow`, `PartitionScheduler`, `PartitionSchedulerOptions`, `RelayerConfiguration`, `RelayerInfrastructureExtensions`, `RelayerInstrumentation`, `RouteDefinition`, `SendTracing`, `TransportCapabilities`, `TransportDefinition`, `TransportServiceProviderExtensions`. | +| `Relayer.Transports` | Native bindings, envelope I/O, scheduling, adapter telemetry, configuration definitions and persistence integration: `ConsumerDefinition`, `ConsumptionModel`, `DeadLetterInfo`, `Disposition`, `DispositionKind`, `EndpointTelemetry`, `EndpointTelemetryOptions`, `FailureMessageCopyDelegate`, `HeaderNames`, `IConsumerDefinition`, `IFailureScheduler`, `IMessageBinding`, `IMessageHeaderReader`, `IMessageHeaderWriter`, `IOutboxEnlistment`, `IOutboxStore`, `IPartitionMessageBinding`, `IPartitionSource`, `IRelayerInfrastructure`, `IRouteDefinition`, `ITransport`, `IBatchSendFailure`, `ITransportCapabilityInitializer`, `ITransportSendTracing`, `MessageCreationContext`, `MessageEnvelope`, `MessageEnvelopeMetadata`, `MessageHeaders`, `MessageOperationTracing`, `MessageTraceData`, `MessageTracing`, `MessagingEndpoint`, `MessagingOperation`, `NativeMessage`, `NativeSendOptionsExtensions`, `OutboxClaim`, `OutboxHeaders`, `OutboxReadRequest`, `OutboxRecord`, `OutgoingMessage`, `PartitionAssignmentToken`, `PartitionCompletionToken`, `PartitionCompletionWindow`, `PartitionScheduler`, `PartitionSchedulerOptions`, `RelayerConfiguration`, `RelayerInfrastructureExtensions`, `RelayerInstrumentation`, `RouteDefinition`, `SendTracing`, `TransportCapabilities`, `TransportDefinition`, `TransportServiceProviderExtensions`. | Serialization SPI remains in `Relayer.Serialization`, and in-memory transport types remain in `Relayer.InMemory`. Other packages keep their existing focused namespaces. @@ -95,6 +95,13 @@ dead-letter management and circuit pause/resume are advertised only by adapters implement them with native facilities. Do not synthesize missing broker features to make a capability table look uniform. +A batch exception can implement `IBatchSendFailure` when the native client reports individual +successes. `IsConfirmed(index)` uses zero-based indexes into the original `SendBatchAsync` input, +including earlier completed destination groups and native chunks. Return true only for native +confirmed successes; false includes both rejected and uncertain outcomes. Outbox dispatch completes +confirmed rows without resending them and isolates the other rows with bounded native single sends. +Do not infer delivery from aggregate exceptions or cancellation. + ## Registration `RelayerInfrastructureExtensions.AddTransport` is the core seam for a transport package's typed registration extension. It declares routes and consumers; it does not substitute for a native client or start a broker receive loop. The application-side call site is in [Configuration](../guides/configuration.md), with executable coverage in `BuilderTests`.