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
14 changes: 10 additions & 4 deletions benchmarks/Relayer.Benchmarks/BatchConsumePipelineBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public void Setup()
new("messaging.destination.name", "source"), new("messaging.batch.message_count", BatchSize)
];
_pipeline = new ConsumePipelineBuilder(_scopes, _provider.GetRequiredService<MessageTypeRegistry>(), _serializer,
static (_, error, _) => ValueTask.FromException(error)).BuildBatch(_descriptor, definition, _source);
static (_, _, _) => default).BuildBatch(_descriptor, definition, _source);
_message = new() { MessageId = "benchmark", MessageType = new("benchmark.batch", 1), Body = ReadOnlySequence<byte>.Empty,
Headers = Tracing != TracingMode.None ? new TraceHeaders(Tracing == TracingMode.Utf8) : null };
_contexts = new DefaultMessageContext[BatchSize];
Expand All @@ -81,6 +81,7 @@ public void Setup()
[Benchmark(Baseline = true)]
public async ValueTask DirectScopedBatch()
{
_handler.FailLastItem = false;
using var activity = StartDirectActivity();
var scope = new AsyncServiceScope(_scopes.CreateScope());
try
Expand All @@ -105,11 +106,13 @@ public async ValueTask DirectScopedBatch()
}

[Benchmark]
[Arguments(false)]
[Arguments(true)]
public async ValueTask ComposedBatch(bool manualCompletion)
[Arguments(false, false)]
[Arguments(true, false)]
[Arguments(false, true)]
public async ValueTask ComposedBatch(bool manualCompletion, bool failLastItem)
{
_handler.ManualCompletion = manualCompletion;
_handler.FailLastItem = failLastItem;
for (var i = 0; i < BatchSize; i++) _contexts[i] = _pipeline.RentContext(_message);
try { await _pipeline.ProcessBatchAsync(_contexts).ConfigureAwait(false); }
finally
Expand All @@ -133,6 +136,8 @@ public sealed class Handler : IBatchHandler<Payload>
{
public int Total { get; private set; }
public bool ManualCompletion { get; set; }
public bool FailLastItem { get; set; }
private readonly Exception _error = new InvalidOperationException("benchmark failure");
public ValueTask<BatchResult> HandleAsync(Batch<Payload> batch, CancellationToken cancellationToken)
{
var total = 0;
Expand All @@ -141,6 +146,7 @@ public ValueTask<BatchResult> HandleAsync(Batch<Payload> batch, CancellationToke
total += batch.Items[i].Message.Value;
if (ManualCompletion) batch.Items[i].Context.Features.GetRequired<ISettlementFeature>().Complete();
}
if (FailLastItem) batch.Items[batch.Count - 1].Fail(_error);
Total = total;
return new(BatchResult.Success);
}
Expand Down
12 changes: 12 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ To change a decision, add a new entry that supersedes it rather than editing his
| [D73](#d73-postgresql-retryable-outbox-sends-retain-durable-eligibility) | PostgreSQL retryable outbox sends retain durable eligibility | Accepted |
| [D74](#d74-portable-consumer-failure-declarations) | Portable consumer failure declarations | Accepted |
| [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 |

---

Expand Down Expand Up @@ -1809,3 +1811,13 @@ with `Relayer.Outbox.PostgreSql.EntityFrameworkCore` and rebuild because registr
assemblies. Existing namespaces, option types and method call sites remain. SQL Server and MySQL EF
support is still planned; the site's [support matrix](../website/docs/reference/outbox-stores.md#database-integration-support)
is the source of truth for available combinations.

## D77. Batch items report their own failures

**Status:** Accepted; supersedes D5's `BatchResult` representation of per-message failures.

**Context.** Index-keyed failure dictionaries can attribute an in-range index from a reordered or filtered collection to the wrong delivery. This is application handler association, not a native broker capability.

**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.
11 changes: 8 additions & 3 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -258,12 +258,17 @@ public sealed class OrderPlacedHandler(AppDbContext db, ISender sender) : IHandl
There are also batch handlers. Each message in a batch can succeed or fail independently, and the transport settles each message natively.

```csharp
public sealed class AuditHandler : IBatchHandler<AuditEvent>
public sealed class AuditHandler(AuditStore store) : IBatchHandler<AuditEvent>
{
public async ValueTask<BatchResult> HandleAsync(Batch<AuditEvent> batch, CancellationToken ct)
{
var failures = await _store.WriteAsync(batch.Items, ct);
return BatchResult.PartialFailure(failures); // only the failed messages are retried
foreach (var item in batch.Items)
{
try { await store.WriteAsync(item.Message, ct); }
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
catch (Exception error) { item.Fail(error); }
}
return BatchResult.Success; // only the failed items are retried
}
}
```
Expand Down
45 changes: 34 additions & 11 deletions src/Relayer/Handling/Batch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,24 +14,47 @@ public sealed record Batch<TMessage>(IReadOnlyList<BatchItem<TMessage>> Items)
/// <typeparam name="TMessage">The message type.</typeparam>
/// <param name="Message">The deserialized message.</param>
/// <param name="Context">The message context.</param>
public readonly record struct BatchItem<TMessage>(TMessage Message, MessageContext Context);
public readonly record struct BatchItem<TMessage>(TMessage Message, MessageContext Context)
{
private readonly IBatchItemFailureTarget? _failures;
private readonly long _generation;
private readonly int _index;

internal BatchItem(TMessage message, MessageContext context, IBatchItemFailureTarget failures, long generation, int index)
: this(message, context) => (_failures, _generation, _index) = (failures, generation, index);

/// <summary>Marks this delivery as failed. Other items can still succeed.</summary>
/// <remarks>Valid only during the handler invocation that supplied this item. Do not retain items or use them after returning.</remarks>
/// <exception cref="InvalidOperationException">The item was not supplied by an active handler invocation.</exception>
public void Fail(Exception exception)
{
ArgumentNullException.ThrowIfNull(exception);
if (_failures is null)
throw new InvalidOperationException("Only items supplied to an active batch handler can be marked as failed.");
_failures.Fail(_generation, _index, exception);
}
}

internal interface IBatchItemFailureTarget
{
void Fail(long generation, int index, Exception exception);
}

/// <summary>The outcome of handling a batch.</summary>
public sealed class BatchResult
{
private BatchResult(IReadOnlyDictionary<int, Exception> failures) => Failures = failures;
private BatchResult(Exception? error) => Error = error;

/// <summary>Every message succeeded.</summary>
public static BatchResult Success { get; } = new(new Dictionary<int, Exception>());
/// <summary>All items not explicitly marked with <c>item.Fail(exception)</c> succeeded.</summary>
public static BatchResult Success { get; } = new(null);

/// <summary>Failures keyed by index within the batch. These messages enter the failure pipeline.</summary>
/// <remarks>A partial failure with buffered direct sends fails the whole attempt because sends cannot be attributed to individual items.</remarks>
public IReadOnlyDictionary<int, Exception> Failures { get; }
/// <summary>The exception that fails every item, or null when only explicitly marked items failed.</summary>
public Exception? Error { get; }

/// <summary>Reports that the messages at the given indexes failed.</summary>
public static BatchResult PartialFailure(IReadOnlyDictionary<int, Exception> failures)
/// <summary>Reports that every item in the invocation failed.</summary>
public static BatchResult Failure(Exception exception)
{
ArgumentNullException.ThrowIfNull(failures);
return failures.Count == 0 ? Success : new BatchResult(failures);
ArgumentNullException.ThrowIfNull(exception);
return new BatchResult(exception);
}
}
27 changes: 20 additions & 7 deletions src/Relayer/Pipeline/BatchDispatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ internal override async ValueTask InvokeAsync(ReadOnlyMemory<DefaultMessageConte
Memory<Exception?> errors, CancellationToken cancellationToken)
{
var state = Rent();
state.Begin(errors);
try
{
for (var i = 0; i < contexts.Length; i++)
Expand All @@ -46,7 +47,7 @@ internal override async ValueTask InvokeAsync(ReadOnlyMemory<DefaultMessageConte
{
var message = _upcastReaders is { } readers && readers.TryGetValue(context.MessageType, out var reader)
? reader.Read(context) : _reader.Read(context);
state.Items[state.Count] = new(message, context);
state.Items[state.Count] = new(message, context, state, state.Generation, i);
state.Indexes[state.Count++] = i;
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
Expand All @@ -59,21 +60,19 @@ internal override async ValueTask InvokeAsync(ReadOnlyMemory<DefaultMessageConte
var handler = _descriptor.Resolve(contexts.Span[0].Services);
result = await _descriptor.DispatchAsync(handler, state.Batch, cancellationToken).ConfigureAwait(false);
ArgumentNullException.ThrowIfNull(result);
if (result.Failures.Count == 0) return;
foreach (var failure in result.Failures)
if ((uint)failure.Key >= (uint)state.Count || failure.Value is null)
throw new InvalidOperationException("BatchResult failures must contain valid batch indexes and non-null exceptions.");
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; }
catch (Exception error)
{
for (var i = 0; i < state.Count; i++) errors.Span[state.Indexes[i]] = error;
return;
}
foreach (var failure in result.Failures) errors.Span[state.Indexes[failure.Key]] = failure.Value;
if (result.Error is { } failure)
for (var i = 0; i < state.Count; i++) errors.Span[state.Indexes[i]] = failure;
}
finally
{
state.End();
Array.Clear(state.Items, 0, state.Count);
state.Count = 0;
for (var i = 0; i < _states.Length; i++)
Expand All @@ -88,8 +87,22 @@ private State Rent()
return new State(_size);
}

private sealed class State : IReadOnlyList<BatchItem<TMessage>>
private sealed class State : IReadOnlyList<BatchItem<TMessage>>, IBatchItemFailureTarget
{
private Memory<Exception?> _errors;
internal long Generation { get; private set; }
internal void Begin(Memory<Exception?> errors)
{
Generation = checked(Generation + 1);
_errors = errors;
}
internal void End() => _errors = default;
public void Fail(long generation, int index, Exception exception)
{
if (generation != Generation || _errors.IsEmpty)
throw new InvalidOperationException("A batch item can only be marked as failed during the handler invocation that supplied it.");
_errors.Span[index] = exception;
}
internal readonly BatchItem<TMessage>[] Items;
internal readonly int[] Indexes;
internal readonly Batch<TMessage> Batch;
Expand Down
7 changes: 5 additions & 2 deletions tests/Relayer.Testing.Tests/HarnessTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,9 @@ public sealed class OtherProbeHandler : IHandler<OtherProbe>

public sealed class BatchProbeHandler : IBatchHandler<Probe>
{
public ValueTask<BatchResult> HandleAsync(Batch<Probe> batch, CancellationToken cancellationToken) =>
new(BatchResult.PartialFailure(new Dictionary<int, Exception> { [1] = new InvalidOperationException("partial") }));
public ValueTask<BatchResult> HandleAsync(Batch<Probe> batch, CancellationToken cancellationToken)
{
batch.Items[1].Fail(new InvalidOperationException("partial"));
return new(BatchResult.Success);
}
}
Loading
Loading