From 5ab54b31cf2e3a1dafdf42527686bd57c0725434 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:07:37 +0000 Subject: [PATCH 1/5] feat: execute generated batch handlers with durable per-message results (#11) --- .../BatchConsumePipelineBenchmarks.cs | 110 ++++ docs/decisions.md | 27 + src/Relayer/Handling/HandlerDescriptor.cs | 6 + src/Relayer/Pipeline/BatchDispatcher.cs | 98 ++++ src/Relayer/Pipeline/BatchExecution.cs | 204 ++++++++ src/Relayer/Pipeline/BatchReceiveExecutor.cs | 101 ++++ src/Relayer/Pipeline/ConsumePipeline.cs | 33 +- .../Pipeline/ConsumePipelineBuilder.cs | 28 + src/Relayer/Pipeline/DefaultMessageContext.cs | 3 +- src/Relayer/Pipeline/ReceivePipeline.cs | 84 ++- src/Relayer/Sending/AttemptSendBuffer.cs | 1 + tests/Relayer.AotSmoke/Program.cs | 17 + tests/Relayer.Tests/BatchPipelineTests.cs | 493 ++++++++++++++++++ .../BatchReceiveExecutorTests.cs | 136 +++++ website/docs/guides/configuration.md | 7 + website/docs/guides/handlers.md | 18 + website/docs/roadmap.md | 1 + website/docs/transports/consume-pipeline.md | 79 +++ website/docs/transports/receive.md | 2 +- website/src/pages/index.js | 1 + 20 files changed, 1443 insertions(+), 6 deletions(-) create mode 100644 benchmarks/Relayer.Benchmarks/BatchConsumePipelineBenchmarks.cs create mode 100644 src/Relayer/Pipeline/BatchDispatcher.cs create mode 100644 src/Relayer/Pipeline/BatchExecution.cs create mode 100644 src/Relayer/Pipeline/BatchReceiveExecutor.cs create mode 100644 tests/Relayer.Tests/BatchPipelineTests.cs create mode 100644 tests/Relayer.Tests/BatchReceiveExecutorTests.cs diff --git a/benchmarks/Relayer.Benchmarks/BatchConsumePipelineBenchmarks.cs b/benchmarks/Relayer.Benchmarks/BatchConsumePipelineBenchmarks.cs new file mode 100644 index 000000000..6ca37ca16 --- /dev/null +++ b/benchmarks/Relayer.Benchmarks/BatchConsumePipelineBenchmarks.cs @@ -0,0 +1,110 @@ +using System.Buffers; +using BenchmarkDotNet.Attributes; +using Microsoft.Extensions.DependencyInjection; +using Relayer.Serialization; + +namespace Relayer.Benchmarks; + +/// Batch composition versus the same scoped sender, serializer and generated handler dispatch. +/// Results are per batch. DI scope allocations are shared by both paths; payload instances are cached. +[MemoryDiagnoser] +public class BatchConsumePipelineBenchmarks +{ + private ServiceProvider _provider = null!; + private IServiceScopeFactory _scopes = null!; + private ConsumePipeline _pipeline = null!; + private BatchHandlerDescriptor _descriptor = null!; + private readonly Serializer _serializer = new(); + private readonly DirectContext _directContext = new(); + private Batch _directBatch = null!; + private ConsumeMessage _message; + private DefaultMessageContext[] _contexts = null!; + + [Params(1, 10, 100)] + public int BatchSize { get; set; } + + [GlobalSetup] + public void Setup() + { + var services = new ServiceCollection(); + services.AddSingleton(_serializer); + services.AddSingleton(); + services.AddRelayer(builder => + { + builder.MessageTypes.Add("benchmark.batch"); + builder.AddTransport("benchmark", transport => + transport.Consume("source", consumer => consumer.Handler().Batch(BatchSize, TimeSpan.FromMilliseconds(100)))); + }); + _provider = services.BuildServiceProvider(); + _scopes = _provider.GetRequiredService(); + _descriptor = _provider.GetRequiredService().GetBatchHandler(); + var definition = _provider.GetRequiredService().Transports[0].Consumers[0]; + _pipeline = new ConsumePipelineBuilder(_scopes, _provider.GetRequiredService(), _serializer, + static (_, error, _) => ValueTask.FromException(error)).BuildBatch(_descriptor, definition); + _message = new() { MessageId = "benchmark", MessageType = new("benchmark.batch", 1), Body = ReadOnlySequence.Empty }; + _contexts = new DefaultMessageContext[BatchSize]; + var items = new BatchItem[BatchSize]; + for (var i = 0; i < items.Length; i++) items[i] = new(_serializer.Deserialize(_message.Body), _directContext); + _directBatch = new(items); + } + + [Benchmark(Baseline = true)] + public async ValueTask DirectScopedBatch() + { + var scope = new AsyncServiceScope(_scopes.CreateScope()); + try + { + _directContext.Provider = scope.ServiceProvider; + _ = scope.ServiceProvider.GetRequiredService(); + for (var i = 0; i < BatchSize; i++) _ = _serializer.Deserialize(_message.Body); + await _descriptor.DispatchAsync(_descriptor.Resolve(scope.ServiceProvider), _directBatch, default).ConfigureAwait(false); + } + finally { await scope.DisposeAsync().ConfigureAwait(false); } + } + + [Benchmark] + public async ValueTask ComposedBatch() + { + for (var i = 0; i < BatchSize; i++) _contexts[i] = _pipeline.RentContext(_message); + try { await _pipeline.ProcessBatchAsync(_contexts).ConfigureAwait(false); } + finally + { + for (var i = 0; i < BatchSize; i++) { _contexts[i].Dispose(); _contexts[i] = null!; } + } + } + + [GlobalCleanup] + public void Cleanup() => _provider.Dispose(); + public sealed class Options; + [Message("benchmark.batch")] + public sealed class Payload { public int Value => 42; } + public sealed class Handler : IBatchHandler + { + public int Total { get; private set; } + public ValueTask HandleAsync(Batch batch, CancellationToken cancellationToken) + { + var total = 0; + for (var i = 0; i < batch.Count; i++) total += batch.Items[i].Message.Value; + Total = total; + return new(BatchResult.Success); + } + } + private sealed class Serializer : IMessageSerializer + { + private readonly Payload _payload = new(); + public string ContentType => "benchmark/cached"; + public TMessage Deserialize(ReadOnlySequence source) => (TMessage)(object)_payload; + public void Serialize(TMessage message, IBufferWriter destination) => throw new NotSupportedException(); + } + private sealed class DirectContext : MessageContext + { + public IServiceProvider Provider { get; set; } = null!; + public override string MessageId => "benchmark"; + public override MessageType MessageType => new("benchmark.batch", 1); + public override MessageHeaders Headers => MessageHeaders.Empty; + public override int Attempt => 1; + public override IServiceProvider Services => Provider; + public override MessageFeatures Features { get; } = new(); + public override CancellationToken CancellationToken => default; + } +} diff --git a/docs/decisions.md b/docs/decisions.md index 7708f388e..9faf60fc9 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -38,6 +38,7 @@ To change a decision, add a new entry that supersedes it rather than editing his | [D25](#d25-telemetry-follows-the-opentelemetry-messaging-span-model) | Telemetry follows the OpenTelemetry messaging span model | Accepted | | [D26](#d26-generate-default-json-metadata-with-the-official-systemtextjson-generator) | Generate default JSON metadata with the official System.Text.Json generator | Accepted | | [D27](#d27-configuration-declarations-are-independent-of-pipeline-execution) | Configuration declarations are independent of pipeline execution | Accepted | +| [D28](#d28-a-batch-attempt-owns-one-scope-and-one-direct-send-buffer) | A batch attempt owns one scope and one direct-send buffer | Accepted | --- @@ -408,3 +409,29 @@ Refines [D8](#d8-systemtextjson-source-generation-by-default). - Configuration can ship independently, and the receive and send pipelines consume its immutable declaration lists during composition. - Native option objects retain their own mutability semantics. Reload updates named options, not routing or topology, and cannot silently restart a native client. - The current core example uses the generic transport-author seam; native registration extensions arrive with their adapters. + +## D28. A batch attempt owns one scope and one direct-send buffer + +**Context.** Batch handlers can report per-message failures, but a scoped `ISender` +belongs to the whole handler invocation. A direct send cannot be attributed to a +successful or failed batch item without a second, implicit message context. + +**Decision.** +- Compose a homogeneous generated batch handler with the consumer's existing size, + wait, and concurrency declaration. Each batch attempt uses one fresh async DI scope. +- Retry only failed items. Dispose the attempt's scope before final failure work, + direct-send flush, or publication of settlement decisions. +- Buffer direct sends for the attempt. Flush only a wholly successful attempt; + discard a wholly failed attempt's buffer. If partial success has buffered direct + sends, fail the receive call without publishing dispositions. Do not guess which + item produced a send or silently lose successful items' sends. +- Handlers that need partial success with outgoing messages use explicit durable + per-message outbox transactions. At-least-once native redelivery still applies + if later failure work or scope disposal fails. +- Native batch receive and core accumulation are explicit executors selected before + receives start. Declaring a capability or batch size never supplies an executor. + +**Consequences.** Successful deliveries never settle before scope disposal and all +required durable work. A failed batch call can repeat already durable work on native +redelivery, as expected for at-least-once delivery. The core does not invent native +settlement or per-message ambient sender semantics. diff --git a/src/Relayer/Handling/HandlerDescriptor.cs b/src/Relayer/Handling/HandlerDescriptor.cs index cdc946d32..62aeca1fb 100644 --- a/src/Relayer/Handling/HandlerDescriptor.cs +++ b/src/Relayer/Handling/HandlerDescriptor.cs @@ -22,6 +22,9 @@ public abstract class HandlerDescriptor(Type handlerType, Type messageType, bool internal virtual ConsumeDelegate CreateConsumeDelegate(IMessageSerializer serializer) => throw new InvalidOperationException("A batch handler cannot be composed as a single-message consumer."); + + internal virtual BatchDispatcher CreateBatchDispatcher(IMessageSerializer serializer, int size, int concurrency) + => throw new InvalidOperationException("Select a generated batch handler when composing batch consumption."); } /// A generated, typed single-message dispatcher. Cache it when composing the pipeline. @@ -63,4 +66,7 @@ public abstract class BatchHandlerDescriptor(Type handlerType) /// Invokes the resolved handler, preserving its per-message results. public abstract ValueTask DispatchAsync( IHandlerMarker handler, Batch batch, CancellationToken cancellationToken); + + internal sealed override BatchDispatcher CreateBatchDispatcher(IMessageSerializer serializer, int size, int concurrency) + => new BatchDispatcher(this, serializer, size, concurrency); } diff --git a/src/Relayer/Pipeline/BatchDispatcher.cs b/src/Relayer/Pipeline/BatchDispatcher.cs new file mode 100644 index 000000000..422660576 --- /dev/null +++ b/src/Relayer/Pipeline/BatchDispatcher.cs @@ -0,0 +1,98 @@ +using System.Collections; +using System.Runtime.CompilerServices; +using Relayer.Serialization; + +namespace Relayer; + +internal abstract class BatchDispatcher +{ + internal abstract ValueTask InvokeAsync(ReadOnlyMemory contexts, + Memory errors, CancellationToken cancellationToken); +} + +internal sealed class BatchDispatcher : BatchDispatcher +{ + private readonly BatchHandlerDescriptor _descriptor; + private readonly IMessageSerializer _serializer; + private readonly State?[] _states; + private readonly int _size; + + internal BatchDispatcher(BatchHandlerDescriptor descriptor, IMessageSerializer serializer, int size, int concurrency) + { + _descriptor = descriptor; + _serializer = serializer; + _size = size; + _states = new State[concurrency]; + for (var i = 0; i < concurrency; i++) _states[i] = new State(size); + } + + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] + internal override async ValueTask InvokeAsync(ReadOnlyMemory contexts, + Memory errors, CancellationToken cancellationToken) + { + var state = Rent(); + try + { + for (var i = 0; i < contexts.Length; i++) + { + var context = contexts.Span[i]; + try + { + var message = _serializer.Deserialize(context.Body); + state.Items[state.Count] = new(message, context); + state.Indexes[state.Count++] = i; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } + catch (Exception error) { errors.Span[i] = new MessageDeserializationException(context.MessageType, error); } + } + if (state.Count == 0) return; + BatchResult result; + try + { + 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; + } + finally + { + Array.Clear(state.Items, 0, state.Count); + state.Count = 0; + for (var i = 0; i < _states.Length; i++) + if (Interlocked.CompareExchange(ref _states[i], state, null) is null) break; + } + } + + private State Rent() + { + for (var i = 0; i < _states.Length; i++) + if (Interlocked.Exchange(ref _states[i], null) is { } state) return state; + return new State(_size); + } + + private sealed class State : IReadOnlyList> + { + internal readonly BatchItem[] Items; + internal readonly int[] Indexes; + internal readonly Batch Batch; + internal State(int size) { Items = new BatchItem[size]; Indexes = new int[size]; Batch = new(this); } + public int Count { get; internal set; } + public BatchItem this[int index] => (uint)index < (uint)Count ? Items[index] : throw new ArgumentOutOfRangeException(nameof(index)); + public IEnumerator> GetEnumerator() + { + for (var i = 0; i < Count; i++) yield return Items[i]; + } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + } +} diff --git a/src/Relayer/Pipeline/BatchExecution.cs b/src/Relayer/Pipeline/BatchExecution.cs new file mode 100644 index 000000000..4ca94cff2 --- /dev/null +++ b/src/Relayer/Pipeline/BatchExecution.cs @@ -0,0 +1,204 @@ +using System.Diagnostics; +using System.Runtime.CompilerServices; +using Microsoft.Extensions.DependencyInjection; + +namespace Relayer; + +internal sealed class BatchExecution +{ + private readonly IServiceScopeFactory _scopes; + private readonly BatchDispatcher _dispatch; + private readonly MessageType _identity; + private readonly ConsumeFailureDelegate _failure; + private readonly IFailureClassifier _classifier; + private readonly FailurePipeline? _failures; + private readonly ActivitySource? _source; + private readonly string _spanName; + private readonly string _destination; + private readonly State?[] _states; + internal int Size { get; } + + internal BatchExecution(IServiceScopeFactory scopes, BatchDispatcher dispatch, MessageType identity, + IConsumerDefinition consumer, ConsumeFailureDelegate failure, IFailureClassifier classifier, + FailurePipeline? failures, ActivitySource? source) + { + _scopes = scopes; + _dispatch = dispatch; + _identity = identity; + _failure = failure; + _classifier = classifier; + _failures = failures; + _source = source; + Size = consumer.BatchSize; + _destination = consumer.Source; + _spanName = "process " + consumer.Source; + _states = new State[consumer.Concurrency]; + for (var i = 0; i < _states.Length; i++) _states[i] = new State(Size); + } + + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] + internal async ValueTask ProcessAsync(ConsumePipeline owner, ReadOnlyMemory contexts, CancellationToken cancellationToken) + { + if (contexts.Length > Size) throw new ArgumentOutOfRangeException(nameof(contexts), "Batch exceeds the consumer's configured maximum size."); + if (contexts.IsEmpty) return; + cancellationToken.ThrowIfCancellationRequested(); + var state = Rent(); + var begun = 0; + Activity? activity = null; + try + { + for (; begun < contexts.Length; begun++) + contexts.Span[begun].BeginProcessing(owner); + activity = StartActivity(contexts, state); + var count = 0; + for (var i = 0; i < contexts.Length; i++) + { + var context = contexts.Span[i]; + Exception? error = null; + try + { + context.CancellationToken.ThrowIfCancellationRequested(); + if (context.MessageType != _identity) throw new UnknownMessageTypeException(context.MessageType); + if (_failures is not null) context.InitializeAttempts(); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested || context.CancellationToken.IsCancellationRequested) { throw; } + catch (Exception failure) { error = failure; } + if (error is null) state.Active[count++] = context; + else + { + RecordError(activity, error); + await HandleFailureAsync(context, error).ConfigureAwait(false); + } + } + var retry = 0; + while (count > 0) + { + cancellationToken.ThrowIfCancellationRequested(); + Array.Clear(state.Errors, 0, count); + var scope = new AsyncServiceScope(_scopes.CreateScope()); + Sender? sender = null; + var buffer = state.Active[0].SendBuffer; + try + { + for (var i = 0; i < count; i++) state.Active[i].SetServices(scope.ServiceProvider); + var service = scope.ServiceProvider.GetService(); + if (service is not null && service is not Sender) + throw new InvalidOperationException("Batch execution requires Relayer's scoped ISender to buffer failed-attempt sends."); + sender = (Sender?)service; + if (sender is not null) sender.AttemptBuffer = buffer; + await _dispatch.InvokeAsync(state.Active.AsMemory(0, count), state.Errors.AsMemory(0, count), cancellationToken).ConfigureAwait(false); + } + finally + { + try { await scope.DisposeAsync().ConfigureAwait(false); } + finally { sender?.EndAttempt(); } + } + cancellationToken.ThrowIfCancellationRequested(); + var failed = 0; + for (var i = 0; i < count; i++) if (state.Errors[i] is not null) failed++; + if (failed == 0) await buffer.FlushAsync(cancellationToken).ConfigureAwait(false); + else if (failed < count && !buffer.IsEmpty) + throw new InvalidOperationException("A partially failed batch has buffered sends that cannot be attributed to individual messages. Use per-message durable outbox transactions or return success only after all batch work is durable."); + buffer.Clear(); + var pending = 0; + for (var i = 0; i < count; i++) + { + var context = state.Active[i]; + context.ClearServices(); + if (state.Errors[i] is not { } error) continue; + RecordError(activity, error); + var action = _classifier.Classify(error, context); + if (_failures is not null) + { + _failures.Record(context, error); + if (action == FailureAction.Retry && _failures.CanRetry(retry)) + { + context.NextAttempt(); + state.Active[pending++] = context; + continue; + } + await _failures.HandleAsync(context, error, action).ConfigureAwait(false); + } + else await _failure(context, error, action).ConfigureAwait(false); + } + count = pending; + if (count > 0) await _failures!.WaitRetryAsync(retry++, cancellationToken).ConfigureAwait(false); + } + } + catch (Exception error) + { + RecordError(activity, error); + throw; + } + finally + { + activity?.Dispose(); + for (var i = 0; i < begun; i++) + { + contexts.Span[i].SendBuffer.Clear(); + contexts.Span[i].EndProcessing(); + } + Array.Clear(state.Active); + Array.Clear(state.Errors); + Array.Clear(state.Links); + for (var i = 0; i < _states.Length; i++) + if (Interlocked.CompareExchange(ref _states[i], state, null) is null) break; + } + } + + private async ValueTask HandleFailureAsync(DefaultMessageContext context, Exception error) + { + var action = _classifier.Classify(error, context); + if (_failures is null) await _failure(context, error, action).ConfigureAwait(false); + else + { + _failures.Record(context, error); + await _failures.HandleAsync(context, error, action).ConfigureAwait(false); + } + } + + private static void RecordError(Activity? activity, Exception error) + { + if (activity is null) return; + // Exception type is error-path diagnostic metadata, never a dispatch lookup. + activity.SetTag("error.type", error.GetType().FullName ?? "_OTHER"); + activity.SetStatus(ActivityStatusCode.Error); + } + + private Activity? StartActivity(ReadOnlyMemory contexts, State state) + { + if (_source is null || !_source.HasListeners()) return null; + var count = 0; + for (var i = 0; i < contexts.Length; i++) + { + var headers = contexts.Span[i].Headers; + if (headers.TryGetValue("traceparent", out var parent)) + { + var traceState = headers.TryGetValue("tracestate", out var value) ? value.ToString() : null; + if (ActivityContext.TryParse(parent.ToString(), traceState, true, out var creation)) + state.Links[count++] = new(creation); + } + } + var tags = new ActivityTagsCollection + { + { "messaging.operation.type", "process" }, { "messaging.operation.name", "process" }, + { "messaging.destination.name", _destination }, { "messaging.batch.message_count", contexts.Length } + }; + return _source.StartActivity(_spanName, ActivityKind.Consumer, Activity.Current?.Context ?? default, + tags, new ArraySegment(state.Links, 0, count)); + } + + private State Rent() + { + for (var i = 0; i < _states.Length; i++) + if (Interlocked.Exchange(ref _states[i], null) is { } state) return state; + return new State(Size); + } + + private sealed class State(int size) + { + internal readonly DefaultMessageContext[] Active = new DefaultMessageContext[size]; + internal readonly Exception?[] Errors = new Exception[size]; + internal readonly ActivityLink[] Links = new ActivityLink[size]; + } +} diff --git a/src/Relayer/Pipeline/BatchReceiveExecutor.cs b/src/Relayer/Pipeline/BatchReceiveExecutor.cs new file mode 100644 index 000000000..b0f07041d --- /dev/null +++ b/src/Relayer/Pipeline/BatchReceiveExecutor.cs @@ -0,0 +1,101 @@ +using System.Runtime.CompilerServices; +using Microsoft.Extensions.DependencyInjection; +using Relayer.Transports; + +namespace Relayer; + +/// Receives native deliveries into borrowed caller storage, respecting native count and byte limits. +/// The number written, from zero through destination.Length. +/// +/// Return zero when maximumWait expires without a delivery. Honor cancellation and maximumWait, and do not +/// retain destination. Keep delivered bodies and headers alive until processing and native settlement finish. +/// The client-side executor always passes one slot; a native executor can fill multiple slots. +/// +public delegate ValueTask BatchReceiveDelegate(Memory destination, TimeSpan maximumWait, CancellationToken cancellationToken); + +/// Selects an executable native batch receive or the core's client-side accumulation at startup. +/// +/// Compose before starting receives. Configuration and capabilities alone are not executors. Native batching +/// takes precedence and is capped by both declared limits; native byte limits may return a smaller batch. +/// The fallback accumulates individually received deliveries without changing ordering or settlement. +/// +public sealed class BatchReceiveExecutor +{ + private readonly BatchReceiveDelegate _receive; + private readonly TimeSpan _wait; + private readonly TimeProvider _time; + + /// Validates the endpoint and chooses an available executor for this consumer declaration. + public BatchReceiveExecutor(IServiceProvider services, string transportName, IConsumerDefinition consumer, string consumerName, + BatchReceiveDelegate? nativeReceive = null, BatchReceiveDelegate? singleReceive = null, + TimeProvider? timeProvider = null) + { + ArgumentNullException.ThrowIfNull(services); + ArgumentNullException.ThrowIfNull(consumer); + ArgumentException.ThrowIfNullOrWhiteSpace(transportName); + ArgumentException.ThrowIfNullOrWhiteSpace(consumerName); + ArgumentException.ThrowIfNullOrWhiteSpace(consumer.Source); + var location = $"Consumer '{consumerName}' from '{consumer.Source}' on transport '{transportName}'"; + if (consumer.BatchSize < 1 || consumer.BatchWait <= TimeSpan.Zero) + throw new InvalidOperationException($"{location}: BatchSize must be positive and BatchWait must be positive."); + ITransport? selected = null; + foreach (var transport in services.GetServices()) + { + if (transport.Name != transportName) continue; + if (selected is not null) throw new InvalidOperationException($"{location}: register exactly one named ITransport."); + selected = transport; + } + if (selected is null) throw new InvalidOperationException($"{location}: register a named ITransport adapter."); + var errors = new List(); + var validator = new EndpointCapabilityValidator([selected], errors, services.GetRequiredService()); + var capabilities = validator.GetCapabilities(selected, consumer.Source); + if (errors.Count != 0 || capabilities is null) + throw new InvalidOperationException($"{location}: {string.Join(Environment.NewLine, errors)}"); + UsesNativeBatching = nativeReceive is not null && (capabilities.MaxBatchSize > 1 || consumer.BatchSize == 1); + MaximumSize = UsesNativeBatching ? Math.Min(consumer.BatchSize, capabilities.MaxBatchSize) : consumer.BatchSize; + _receive = (UsesNativeBatching ? nativeReceive : singleReceive) + ?? throw new InvalidOperationException($"{location}: BatchSize {consumer.BatchSize} has no executor. Register native batch receive within MaxBatchSize or a single-message receive executor for core client-side batching."); + _wait = consumer.BatchWait; + _time = timeProvider ?? TimeProvider.System; + } + + /// Whether native batching was selected at startup. + public bool UsesNativeBatching { get; } + /// The effective count limit, capped by the native limit when using native batching. + public int MaximumSize { get; } + + /// Receives one batch. Process only the returned prefix, then settle using the native client. + /// + /// Caller owns all received deliveries even if a later receive fails. On exceptions, drain or release them + /// using the native client's shutdown/redelivery mechanism; never acknowledge them as successful. + /// One call is one receive loop. Concurrent calls require independent destination storage. + /// + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))] + public async ValueTask ReceiveAsync(Memory destination, CancellationToken cancellationToken = default) + { + if (destination.Length < MaximumSize) throw new ArgumentException("Provide storage for MaximumSize deliveries.", nameof(destination)); + cancellationToken.ThrowIfCancellationRequested(); + if (UsesNativeBatching) + { + var nativeCount = ValidateCount(await _receive(destination[..MaximumSize], _wait, cancellationToken).ConfigureAwait(false), MaximumSize); + cancellationToken.ThrowIfCancellationRequested(); + return nativeCount; + } + var count = 0; + long started = 0; + while (count < MaximumSize) + { + var remaining = count == 0 ? _wait : _wait - _time.GetElapsedTime(started); + if (remaining <= TimeSpan.Zero) break; + cancellationToken.ThrowIfCancellationRequested(); + var received = ValidateCount(await _receive(destination.Slice(count, 1), remaining, cancellationToken).ConfigureAwait(false), 1); + cancellationToken.ThrowIfCancellationRequested(); + if (received == 0) break; + if (count++ == 0) started = _time.GetTimestamp(); + } + return count; + } + + private static int ValidateCount(int count, int maximum) => (uint)count <= (uint)maximum ? count + : throw new InvalidOperationException("The receive executor returned a count outside its supplied destination."); +} diff --git a/src/Relayer/Pipeline/ConsumePipeline.cs b/src/Relayer/Pipeline/ConsumePipeline.cs index 6845f8b95..1e0e560eb 100644 --- a/src/Relayer/Pipeline/ConsumePipeline.cs +++ b/src/Relayer/Pipeline/ConsumePipeline.cs @@ -14,6 +14,16 @@ namespace Relayer; /// A consumer's composed middleware and generated dispatch, shared across concurrent deliveries. public sealed class ConsumePipeline { + internal BatchExecution? BatchExecution { get; init; } + + /// Whether this consumer dispatches a generated batch handler. + public bool IsBatch => BatchExecution is not null; + + /// Processes one batch, with one scope per batch attempt and only failed items retried. + /// No native settlement is performed. Keep context memory unchanged until completion. Only use settlement decisions after the entire call succeeds. + public ValueTask ProcessBatchAsync(ReadOnlyMemory contexts, CancellationToken cancellationToken = default) + => (BatchExecution ?? throw new InvalidOperationException("Build a batch consumer before using batch dispatch.")) + .ProcessAsync(this, contexts, cancellationToken); private readonly IServiceScopeFactory _scopes; private readonly FrozenDictionary _dispatch; private readonly ConsumeFailureDelegate _failure; @@ -25,6 +35,7 @@ public sealed class ConsumePipeline private readonly EndpointTelemetry? _telemetry; private readonly ConsumeDelegate? _settlement; internal HeaderNames EnvelopeNames { get; } = new(); + private int _batchCursor; internal ConsumePipeline(IServiceScopeFactory scopes, FrozenDictionary dispatch, IReadOnlyList middleware, ConsumeFailureDelegate failure, IFailureClassifier classifier, @@ -47,7 +58,7 @@ internal ConsumePipeline(IServiceScopeFactory scopes, FrozenDictionary= 0; i--) @@ -70,6 +81,19 @@ public DefaultMessageContext RentContext(in ConsumeMessage message, Cancellation private DefaultMessageContext RentContext() { + if (IsBatch) + { + var start = Volatile.Read(ref _batchCursor); + for (var offset = 0; offset < _contexts.Length; offset++) + { + var index = start + offset; + if (index >= _contexts.Length) index -= _contexts.Length; + if (Interlocked.Exchange(ref _contexts[index], null) is not { } context) continue; + Volatile.Write(ref _batchCursor, index + 1 == _contexts.Length ? 0 : index + 1); + return context; + } + return new DefaultMessageContext(this); + } for (var i = 0; i < _contexts.Length; i++) { if (Interlocked.Exchange(ref _contexts[i], null) is { } context) @@ -119,6 +143,7 @@ internal string GetWireIdentityText(MessageType messageType) /// Cancellation propagates. Failure-pipeline and scope-disposal errors propagate, preventing successful settlement. public ValueTask ProcessAsync(DefaultMessageContext context) { + if (IsBatch) throw new InvalidOperationException("Use ProcessBatchAsync for a batch consumer."); ArgumentNullException.ThrowIfNull(context); context.BeginProcessing(this); return _failures is null ? ProcessCoreAsync(context) : ProcessWithFailuresAsync(context); @@ -307,6 +332,12 @@ private static void LogFailure(EndpointTelemetry? telemetry, DefaultMessageConte internal void Return(DefaultMessageContext context) { + if (IsBatch) + { + // Batch rentals retain their original slot, avoiding a scan for each item in a full batch. + if (context.PoolSlot >= 0) Interlocked.CompareExchange(ref _contexts[context.PoolSlot], context, null); + return; + } for (var i = 0; i < _contexts.Length; i++) { if (Interlocked.CompareExchange(ref _contexts[i], context, null) is null) return; diff --git a/src/Relayer/Pipeline/ConsumePipelineBuilder.cs b/src/Relayer/Pipeline/ConsumePipelineBuilder.cs index d9aa3a0f2..088ecfd5a 100644 --- a/src/Relayer/Pipeline/ConsumePipelineBuilder.cs +++ b/src/Relayer/Pipeline/ConsumePipelineBuilder.cs @@ -19,6 +19,34 @@ public sealed class ConsumePipelineBuilder private EndpointTelemetry? _telemetry; private ConsumeDelegate? _settlement; + /// Builds a homogeneous batch consumer using its existing size, wait and concurrency declaration. + /// Batch handlers coordinate their own per-message work. Single-message middleware, telemetry, and settlement callbacks cannot be combined with batch composition. + public ConsumePipeline BuildBatch(HandlerDescriptor descriptor, IConsumerDefinition consumer, + System.Diagnostics.ActivitySource? activitySource = null) + { + EnsureMutable(); + ArgumentNullException.ThrowIfNull(descriptor); + ArgumentNullException.ThrowIfNull(consumer); + if (_telemetry is not null || _settlement is not null) + throw new InvalidOperationException("Batch consumers do not support single-message telemetry or settlement callbacks. Record telemetry and settle native deliveries around ProcessBatchAsync."); + if (_dispatch.Count != 0 || _middleware.Count != 0) + throw new InvalidOperationException("Compose batch handlers separately from single-message handlers and middleware."); + if (!_messages.IsFrozen || !_messages.TryGetMessageType(descriptor.MessageType, out var identity)) + throw new InvalidOperationException("Register and freeze the batch message's stable wire identity before composition."); + ArgumentOutOfRangeException.ThrowIfLessThan(consumer.BatchSize, 1); + ArgumentOutOfRangeException.ThrowIfLessThan(consumer.Concurrency, 1); + if (consumer.BatchWait <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(consumer)); + var batch = descriptor.CreateBatchDispatcher(_serializer, consumer.BatchSize, consumer.Concurrency); + using (var scope = _scopes.CreateScope()) scope.ServiceProvider.GetService()?.Enable(); + _built = true; + var identities = new Dictionary { [identity] = static _ => throw new InvalidOperationException("Use ProcessBatchAsync for a batch handler.") }; + return new ConsumePipeline(_scopes, identities.ToFrozenDictionary(), [], _failure, _classifier, + checked(consumer.BatchSize * consumer.Concurrency), _failures, null, null) + { + BatchExecution = new BatchExecution(_scopes, batch, identity, consumer, _failure, _classifier, _failures, activitySource) + }; + } + /// Creates a consumer composer with an explicit failure pipeline. /// The failure delegate must finish durable failure handling before returning successfully. public ConsumePipelineBuilder(IServiceScopeFactory scopes, MessageTypeRegistry messages, diff --git a/src/Relayer/Pipeline/DefaultMessageContext.cs b/src/Relayer/Pipeline/DefaultMessageContext.cs index 3b26e8216..5b8a31d7a 100644 --- a/src/Relayer/Pipeline/DefaultMessageContext.cs +++ b/src/Relayer/Pipeline/DefaultMessageContext.cs @@ -12,7 +12,8 @@ public sealed class DefaultMessageContext : MessageContext, IDisposable // 0: pooled, 1: rented, 2: processing, 3: processed. A delivery can run only once. private int _state; - internal DefaultMessageContext(ConsumePipeline owner) => _owner = owner; + internal int PoolSlot { get; } + internal DefaultMessageContext(ConsumePipeline owner, int poolSlot = -1) { _owner = owner; PoolSlot = poolSlot; } /// public override string MessageId => _receive?.MessageId ?? _message.MessageId; diff --git a/src/Relayer/Pipeline/ReceivePipeline.cs b/src/Relayer/Pipeline/ReceivePipeline.cs index 08ba1541c..52a162d1a 100644 --- a/src/Relayer/Pipeline/ReceivePipeline.cs +++ b/src/Relayer/Pipeline/ReceivePipeline.cs @@ -16,6 +16,8 @@ public sealed class ReceivePipeline private readonly ConsumePipeline _consumer; private readonly HeaderNames _names; private readonly State?[] _states; + private readonly BatchState?[] _batches; + private int _batchCursor; /// Adapts a consumer with its transport's CloudEvents header binding. public ReceivePipeline(ConsumePipeline consumer, HeaderNames names, int contextPoolCapacity = 64) @@ -26,7 +28,10 @@ public ReceivePipeline(ConsumePipeline consumer, HeaderNames names, int contextP _consumer = consumer; _names = names; _states = new State[contextPoolCapacity]; - for (var i = 0; i < _states.Length; i++) _states[i] = new State(consumer, names); + for (var i = 0; i < _states.Length; i++) _states[i] = new State(consumer, names, i); + _batches = consumer.BatchExecution is { } batch + ? new BatchState[Math.Max(1, contextPoolCapacity / batch.Size)] : []; + for (var i = 0; i < _batches.Length; i++) _batches[i] = new BatchState(consumer.BatchExecution!.Size); } /// Processes one delivery and releases all native references before returning its disposition. @@ -52,7 +57,7 @@ public async ValueTask ProcessAsync(TIncoming message, Cancellation /// Processes deliveries in input order, writing one disposition per delivery. /// - /// This is a transport batch entry point, not batch-handler dispatch. Output may be larger than input; + /// A consumer built with BuildBatch dispatches its generated batch handler; other consumers process deliveries individually. Output may be larger than input; /// its unused tail is untouched. Only settle from this output when the entire call succeeds. /// On failure or cancellation, some earlier deliveries may have completed durable work; native redelivery /// remains at-least-once. Both memories must remain valid and unchanged until the call completes. @@ -64,6 +69,11 @@ public async ValueTask ProcessBatchAsync(ReadOnlyMemory messages, Mem if (dispositions.Length < messages.Length) throw new ArgumentException("Provide at least one disposition slot per incoming message.", nameof(dispositions)); cancellationToken.ThrowIfCancellationRequested(); + if (_consumer.IsBatch) + { + await ProcessHandlerBatchAsync(messages, dispositions, cancellationToken).ConfigureAwait(false); + return; + } for (var i = 0; i < messages.Length; i++) { var disposition = await ProcessAsync(messages.Span[i], cancellationToken).ConfigureAwait(false); @@ -71,8 +81,70 @@ public async ValueTask ProcessBatchAsync(ReadOnlyMemory messages, Mem } } + [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] + private async ValueTask ProcessHandlerBatchAsync(ReadOnlyMemory messages, Memory dispositions, + CancellationToken cancellationToken) + { + var maximum = _consumer.BatchExecution!.Size; + if (messages.Length > maximum) throw new ArgumentOutOfRangeException(nameof(messages), "Batch exceeds the configured maximum size."); + if (messages.IsEmpty) return; + BatchState? batch = null; + for (var i = 0; i < _batches.Length && batch is null; i++) batch = Interlocked.Exchange(ref _batches[i], null); + batch ??= new BatchState(maximum); + var count = 0; + try + { + for (; count < messages.Length; count++) + { + var state = Rent(); + batch.States[count] = state; + state.Initialize(messages.Span[count]); + var context = _consumer.RentContext(state, cancellationToken); + batch.Contexts[count] = context; + context.Features.Set(state.Native); + } + await _consumer.ProcessBatchAsync(batch.Contexts.AsMemory(0, count), cancellationToken).ConfigureAwait(false); + for (var i = 0; i < count; i++) + dispositions.Span[i] = batch.Contexts[i].FailureDisposition ?? batch.States[i]!.Native.Disposition; + } + finally + { + // Include the slot whose native binding or context initialization threw. + for (var i = 0; i < messages.Length; i++) + { + batch.Contexts[i]?.Dispose(); + batch.Contexts[i] = null!; + if (batch.States[i] is not { } state) continue; + state.Clear(); + Return(state); + batch.States[i] = null; + } + for (var i = 0; i < _batches.Length; i++) + if (Interlocked.CompareExchange(ref _batches[i], batch, null) is null) break; + } + } + + private sealed class BatchState(int size) + { + internal readonly DefaultMessageContext[] Contexts = new DefaultMessageContext[size]; + internal readonly State?[] States = new State[size]; + } + private State Rent() { + if (_consumer.IsBatch) + { + var start = Volatile.Read(ref _batchCursor); + for (var offset = 0; offset < _states.Length; offset++) + { + var index = start + offset; + if (index >= _states.Length) index -= _states.Length; + if (Interlocked.Exchange(ref _states[index], null) is not { } state) continue; + Volatile.Write(ref _batchCursor, index + 1 == _states.Length ? 0 : index + 1); + return state; + } + return new State(_consumer, _names); + } for (var i = 0; i < _states.Length; i++) if (Interlocked.Exchange(ref _states[i], null) is { } state) return state; return new State(_consumer, _names); @@ -80,13 +152,19 @@ private State Rent() private void Return(State state) { + if (_consumer.IsBatch) + { + if (state.PoolSlot >= 0) Interlocked.CompareExchange(ref _states[state.PoolSlot], state, null); + return; + } for (var i = 0; i < _states.Length; i++) if (Interlocked.CompareExchange(ref _states[i], state, null) is null) return; } - private sealed class State(ConsumePipeline consumer, HeaderNames names) : ReceiveMessageState + private sealed class State(ConsumePipeline consumer, HeaderNames names, int poolSlot = -1) : ReceiveMessageState { internal override HeaderNames EnvelopeNames => names; + internal int PoolSlot { get; } = poolSlot; private MessageHeaders _headers; private WireString _id; private string? _messageId; diff --git a/src/Relayer/Sending/AttemptSendBuffer.cs b/src/Relayer/Sending/AttemptSendBuffer.cs index 0bb019446..6966aa60e 100644 --- a/src/Relayer/Sending/AttemptSendBuffer.cs +++ b/src/Relayer/Sending/AttemptSendBuffer.cs @@ -8,6 +8,7 @@ internal sealed class AttemptSendBuffer { private readonly Segment _entries = new(); private int _count; + internal bool IsEmpty => _count == 0; internal void Add(ITransport transport, OutgoingMessage message, TimeSpan timeout) { diff --git a/tests/Relayer.AotSmoke/Program.cs b/tests/Relayer.AotSmoke/Program.cs index ef60d7346..ad4cd3361 100644 --- a/tests/Relayer.AotSmoke/Program.cs +++ b/tests/Relayer.AotSmoke/Program.cs @@ -25,6 +25,7 @@ broker.Send("orders", route => route.OrderingKey(static order => order.Id)); broker.Send("counts"); broker.Consume("orders", consumer => consumer.Handler().Handler()); + broker.Consume("counts", consumer => consumer.Handler().Batch(2, TimeSpan.FromMilliseconds(100))); }); builder.UseSendMiddleware(); }).BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); @@ -138,6 +139,22 @@ if (healthy.Kind != DispositionKind.Complete || transport.CapabilityLookups != 2) throw new InvalidOperationException("Failure handling stalled the consumer or rediscovered capabilities."); Console.WriteLine("Executable failure handling and generated error metadata passed under Native AOT."); +var batchDefinition = provider.GetRequiredService().Transports[0].Consumers[1]; +var batchConsumer = new ConsumePipelineBuilder(provider.GetRequiredService(), + provider.GetRequiredService(), serializer, static (_, error, _) => ValueTask.FromException(error)) + .BuildBatch(handlers.GetBatchHandler(), batchDefinition); +var countBuffer = new ArrayBufferWriter(); +serializer.Serialize(new Count(7), countBuffer); +var countMessage = new ConsumeMessage { MessageId = "batch-count", MessageType = new("smoke.count", 1), Body = new(countBuffer.WrittenMemory) }; +var batchReceiver = new BatchReceiveExecutor(provider, "smoke", batchDefinition, "aot-batch", + singleReceive: (destination, _, _) => { destination.Span[0] = countMessage; return new(1); }); +var receivedBatch = new ConsumeMessage[2]; +if (await batchReceiver.ReceiveAsync(receivedBatch) != 2 || batchReceiver.UsesNativeBatching) + throw new InvalidOperationException("Client-side batch execution failed under Native AOT."); +using (var firstCount = batchConsumer.RentContext(receivedBatch[0])) +using (var secondCount = batchConsumer.RentContext(receivedBatch[1])) + await batchConsumer.ProcessBatchAsync(new[] { firstCount, secondCount }); +Console.WriteLine("Generated batch composition and client-side executor passed under Native AOT."); var sender = scope.ServiceProvider.GetRequiredService(); await sender.SendAsync(message, options => options.ConfigureNative(static native => native.Value = 7)); if (transport.Destination != "orders" || transport.OrderingKey != "42" || transport.NativeValue != 7) diff --git a/tests/Relayer.Tests/BatchPipelineTests.cs b/tests/Relayer.Tests/BatchPipelineTests.cs new file mode 100644 index 000000000..811160124 --- /dev/null +++ b/tests/Relayer.Tests/BatchPipelineTests.cs @@ -0,0 +1,493 @@ +using System.Buffers; +using System.Diagnostics; +using Microsoft.Extensions.DependencyInjection; +using Relayer.Serialization; +using Relayer.Transports; + +namespace Relayer.Tests; + +public class BatchPipelineTests +{ + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Batch_composition_rejects_single_message_callbacks(bool telemetry) + { + await using var provider = Provider(); + using var instrumentation = new RelayerInstrumentation(); + var builder = new ConsumePipelineBuilder(provider.GetRequiredService(), + provider.GetRequiredService(), provider.GetRequiredService(), + static (_, error, _) => ValueTask.FromException(error)); + if (telemetry) builder.Telemetry(instrumentation.CreateEndpoint(new() { System = "test" })); + else builder.Settle(static _ => default); + + await Assert.That(() => builder.BuildBatch( + provider.GetRequiredService().GetBatchHandler(), Definition(provider))) + .Throws(); + } + + [Test] + [Arguments(0)] + [Arguments(1)] + [Arguments(2)] + public async Task Full_partial_and_thrown_failure_settle_only_after_scope_and_failure_work(int failureMode) + { + await using var provider = Provider(); + var control = provider.GetRequiredService(); + var handlerDone = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var disposalDone = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + control.Disposal = disposalDone.Task; + control.DisposalStarted = new(TaskCreationOptions.RunContinuationsAsynchronously); + control.Invoke = (_, _) => new(handlerDone.Task); + var failedIds = new List(); + var failureDone = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var failureStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var pipeline = Pipeline(provider, async (context, _, _) => + { + failedIds.Add(context.MessageId); + context.Features.GetRequired>().Disposition = Disposition.DeadLettered(new("failed")); + failureStarted.TrySetResult(); + await failureDone.Task; + }); + var output = Sentinels(3); + var pending = pipeline.ProcessBatchAsync(Input(3), output); + await Assert.That(pending.IsCompleted).IsFalse(); + if (failureMode == 2) handlerDone.SetException(new InvalidOperationException("total failure")); + else handlerDone.SetResult(failureMode == 0 ? BatchResult.Success : BatchResult.PartialFailure(new Dictionary { [1] = new InvalidOperationException("partial") })); + await control.DisposalStarted.Task; + await Assert.That(output.All(d => d.Kind == DispositionKind.SettledByHandler)).IsTrue(); + await Assert.That(failedIds.Count).IsEqualTo(0); + disposalDone.SetResult(); + if (failureMode > 0) + { + await failureStarted.Task; + await Assert.That(pending.IsCompleted).IsFalse(); + await Assert.That(output.All(d => d.Kind == DispositionKind.SettledByHandler)).IsTrue(); + } + failureDone.SetResult(); + await pending; + await Assert.That(string.Join(",", failedIds)).IsEqualTo(failureMode switch { 0 => "", 1 => "1", _ => "0,1,2" }); + for (var i = 0; i < 3; i++) + await Assert.That(output[i].Kind).IsEqualTo(failureMode == 2 || failureMode == 1 && i == 1 ? DispositionKind.DeadLetter : DispositionKind.Complete); + await Assert.That(control.Scopes.Count).IsEqualTo(1); + await Assert.That(control.Disposed).IsEqualTo(1); + } + + [Test] + public async Task Retry_invokes_only_failed_items_in_fresh_scope_with_native_durable_dispositions() + { + await using var provider = Provider(); + var control = provider.GetRequiredService(); + var batches = new List(); + control.Invoke = (batch, _) => + { + batches.Add(string.Join(",", batch.Items.Select(item => item.Context.MessageId + ":" + item.Context.Attempt))); + return new(BatchResult.PartialFailure(new Dictionary { [batch.Count - 1] = new InvalidOperationException("failed") })); + }; + var failures = new FailurePipeline(provider, "test", "source", "batch", new() { RetryDelays = new[] { TimeSpan.Zero }, Jitter = 0 }); + var pipeline = Pipeline(provider, failures: failures); + var output = new Disposition[3]; + await pipeline.ProcessBatchAsync(Input(3), output); + await Assert.That(string.Join(";", batches)).IsEqualTo("0:1,1:1,2:1;2:2"); + await Assert.That(output[0].Kind).IsEqualTo(DispositionKind.Complete); + await Assert.That(output[1].Kind).IsEqualTo(DispositionKind.Complete); + await Assert.That(output[2].Kind).IsEqualTo(DispositionKind.DeadLetter); + await Assert.That(control.Scopes.Count).IsEqualTo(2); + await Assert.That(control.Scopes[0]).IsNotSameReferenceAs(control.Scopes[1]); + await Assert.That(control.Disposed).IsEqualTo(2); + await Assert.That(provider.GetRequiredService().Reads).IsEqualTo(2); // source and route, cached across retry + } + + [Test] + public async Task Poison_items_are_excluded_and_partial_indexes_map_to_original_deliveries() + { + await using var provider = Provider(); + var control = provider.GetRequiredService(); + control.Invoke = (batch, _) => + { + if (string.Join(",", batch.Items.Select(item => item.Context.MessageId)) != "0,3") throw new Exception("Wrong batch"); + return new(BatchResult.PartialFailure(new Dictionary { [1] = new ApplicationException("handler") })); + }; + var errors = new List<(string Id, Exception Error, FailureAction Action)>(); + var input = Input(4); + input[1] = input[1] with { Type = "unknown;v=1" }; + input[2] = input[2] with { Value = 0 }; + var output = new Disposition[4]; + await Pipeline(provider, (context, error, action) => { errors.Add((context.MessageId, error, action)); return default; }).ProcessBatchAsync(input, output); + await Assert.That(string.Join(",", errors.Select(e => e.Id))).IsEqualTo("1,2,3"); + await Assert.That(errors[0].Error is UnknownMessageTypeException).IsTrue(); + await Assert.That(errors[1].Error is MessageDeserializationException).IsTrue(); + await Assert.That(errors[0].Action).IsEqualTo(FailureAction.DeadLetter); + await Assert.That(errors[1].Action).IsEqualTo(FailureAction.DeadLetter); + await Assert.That(errors[2].Action).IsEqualTo(FailureAction.Retry); + } + + [Test] + public async Task Invalid_results_fail_every_item_without_dropping_invalid_indexes() + { + await using var provider = Provider(); + provider.GetRequiredService().Invoke = (_, _) => new(BatchResult.PartialFailure(new Dictionary { [3] = new Exception() })); + var failures = 0; + await Pipeline(provider, (_, _, _) => { failures++; return default; }).ProcessBatchAsync(Input(3), new Disposition[3]); + await Assert.That(failures).IsEqualTo(3); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Disposal_or_failure_executor_errors_leave_output_untouched(bool failDisposal) + { + await using var provider = Provider(); + var control = provider.GetRequiredService(); + if (failDisposal) control.Disposal = Task.FromException(new ApplicationException("dispose")); + else control.Invoke = (_, _) => ValueTask.FromException(new Exception("handler")); + var output = Sentinels(3); + await Assert.That(async () => await Pipeline(provider, (_, _, _) => ValueTask.FromException(new ApplicationException("durability"))) + .ProcessBatchAsync(Input(3), output)).Throws(); + await Assert.That(output.All(d => d.Kind == DispositionKind.SettledByHandler)).IsTrue(); + } + + [Test] + public async Task Cancellation_keeps_output_untouched_and_releases_all_native_references() + { + await using var provider = Provider(); + var control = provider.GetRequiredService(); + var retained = new List>(); + using var cancellation = new CancellationTokenSource(); + control.Invoke = (batch, _) => + { + retained.AddRange(batch.Items.Select(item => item.Context.Features.GetRequired>())); + cancellation.Cancel(); + return ValueTask.FromCanceled(cancellation.Token); + }; + var output = Sentinels(3); + var pipeline = Pipeline(provider); + await Assert.That(async () => await pipeline.ProcessBatchAsync(Input(3), output, cancellation.Token)).Throws(); + await Assert.That(output.All(d => d.Kind == DispositionKind.SettledByHandler)).IsTrue(); + await Assert.That(retained.All(item => item.Message is null)).IsTrue(); + control.Invoke = null; + await pipeline.ProcessBatchAsync(Input(3), output); + await Assert.That(output.All(d => d.Kind == DispositionKind.Complete)).IsTrue(); + } + + [Test] + public async Task Each_batch_owns_one_scope_and_concurrent_batches_do_not_share_storage() + { + await using var provider = Provider(); + var control = provider.GetRequiredService(); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var batches = new List>(); + control.Invoke = (batch, _) => { batches.Add(batch); return new(release.Task); }; + var pipeline = Pipeline(provider); + var first = pipeline.ProcessBatchAsync(Input(3), new Disposition[3]); + var secondInput = Input(2); + secondInput[0] = secondInput[0] with { Id = "second" }; + var second = pipeline.ProcessBatchAsync(secondInput, new Disposition[2]); + await Assert.That(batches[0]).IsNotSameReferenceAs(batches[1]); + await Assert.That(batches[0].Count).IsEqualTo(3); + await Assert.That(batches[1].Items[0].Context.MessageId).IsEqualTo("second"); + release.SetResult(BatchResult.Success); + await first; + await second; + await Assert.That(control.Disposed).IsEqualTo(2); + await Assert.That(batches.All(batch => batch.Count == 0)).IsTrue(); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Batch_span_links_every_creation_context_and_uses_only_ambient_parent(bool ambient) + { + await using var provider = Provider(); + using var source = new ActivitySource("Relayer"); + Activity? observed = null; + using var listener = new ActivityListener + { + ShouldListenTo = candidate => ReferenceEquals(candidate, source), + Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded, + ActivityStopped = activity => observed = activity + }; + ActivitySource.AddActivityListener(listener); + using var parent = ambient ? new Activity("ambient").Start() : null; + var expectedActivity = Activity.Current; + var expectedParent = expectedActivity?.Context ?? default; + var input = Input(3); + await Pipeline(provider, source: source).ProcessBatchAsync(input, new Disposition[3]); + await Assert.That(observed!.DisplayName).IsEqualTo("process source"); + await Assert.That(observed.Kind).IsEqualTo(ActivityKind.Consumer); + await Assert.That(observed.ParentSpanId).IsEqualTo(expectedParent.SpanId); + await Assert.That((int)observed.GetTagItem("messaging.batch.message_count")!).IsEqualTo(3); + await Assert.That(observed.GetTagItem("messaging.operation.type") as string).IsEqualTo("process"); + await Assert.That(observed.Links.Count()).IsEqualTo(3); + await Assert.That(observed.Links.All(link => link.Context.IsRemote)).IsTrue(); + await Assert.That(Activity.Current).IsSameReferenceAs(expectedActivity); + } + + [Test] + public async Task Batch_size_output_and_empty_boundaries_are_enforced() + { + await using var provider = Provider(size: 3); + var pipeline = Pipeline(provider); + await pipeline.ProcessBatchAsync(Input(3), new Disposition[3]); + await pipeline.ProcessBatchAsync(Array.Empty(), Memory.Empty); + await Assert.That(async () => await pipeline.ProcessBatchAsync(Input(4), new Disposition[4])).Throws(); + await Assert.That(async () => await pipeline.ProcessBatchAsync(Input(3), new Disposition[2])).Throws(); + await Assert.That(provider.GetRequiredService().Scopes.Count).IsEqualTo(1); + } + + [Test] + public async Task Buffered_sends_flush_only_after_whole_batch_success_and_disposal() + { + await using var provider = Provider(); + var control = provider.GetRequiredService(); + var transport = provider.GetRequiredService(); + control.Invoke = async (batch, _) => + { + await batch.Items[0].Context.Services.GetRequiredService().SendNowAsync(new Payload()); + await Assert.That(transport.Sends).IsEqualTo(0); + return BatchResult.Success; + }; + await Pipeline(provider).ProcessBatchAsync(Input(3), new Disposition[3]); + await Assert.That(transport.Sends).IsEqualTo(1); + await Assert.That(control.Disposed).IsEqualTo(1); + control.Invoke = async (batch, _) => + { + await batch.Items[0].Context.Services.GetRequiredService().SendNowAsync(new Payload()); + return BatchResult.PartialFailure(new Dictionary { [1] = new Exception("partial") }); + }; + var output = Sentinels(3); + await Assert.That(async () => await Pipeline(provider).ProcessBatchAsync(Input(3), output)).Throws(); + await Assert.That(transport.Sends).IsEqualTo(1); + await Assert.That(output.All(item => item.Kind == DispositionKind.SettledByHandler)).IsTrue(); + } + + [Test] + public async Task Durable_copy_must_finish_before_any_batch_disposition_is_published() + { + await using var provider = Provider(); + var transport = provider.GetRequiredService(); + transport.NativeDeadLetter = false; + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var durable = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + transport.Send = (_, _) => { started.SetResult(); return new(durable.Task); }; + provider.GetRequiredService().Invoke = (_, _) => new(BatchResult.PartialFailure(new Dictionary { [1] = new Exception("failed") })); + var failures = new FailurePipeline(provider, "test", "source", "batch", new() { DeadLetterEndpoint = "dead" }, + context => new("source", new byte[] { 1 }, new[] { new KeyValuePair("ce_id", new(context.MessageId)) })); + var output = Sentinels(3); + var pending = Pipeline(provider, failures: failures).ProcessBatchAsync(Input(3), output); + await started.Task; + await Assert.That(pending.IsCompleted).IsFalse(); + await Assert.That(output.All(item => item.Kind == DispositionKind.SettledByHandler)).IsTrue(); + durable.SetResult(); + await pending; + await Assert.That(output.All(item => item.Kind == DispositionKind.Complete)).IsTrue(); + await Assert.That(transport.Sends).IsEqualTo(1); + } + + [Test] + public async Task Batch_context_ownership_and_single_message_entry_are_validated_before_dispatch() + { + await using var provider = Provider(); + var first = Consumer(provider); + var second = Consumer(provider); + var message = new ConsumeMessage { MessageId = "id", MessageType = new("batch.payload", 1), Body = new(new byte[] { 1 }) }; + using var owned = first.RentContext(message); + using var foreign = second.RentContext(message); + await Assert.That(() => { _ = first.ProcessAsync(owned); }).Throws(); + await Assert.That(async () => await first.ProcessBatchAsync(new[] { owned, foreign })).Throws(); + // Rejection must not consume the foreign rental. + await second.ProcessBatchAsync(new[] { foreign }); + await Assert.That(provider.GetRequiredService().Scopes.Count).IsEqualTo(1); + } + + [Test] + public async Task Warmed_batches_add_no_allocations_beyond_identical_fresh_DI_scope_and_sender() + { + await using var provider = Provider(size: 10); + var scopes = provider.GetRequiredService(); + var consumer = new ConsumePipelineBuilder(scopes, provider.GetRequiredService(), + provider.GetRequiredService(), static (_, error, _) => ValueTask.FromException(error)) + .BuildBatch(provider.GetRequiredService().GetBatchHandler(), Definition(provider)); + var message = new ConsumeMessage { MessageId = "allocation", MessageType = new("batch.payload", 1), Body = new(new byte[] { 1 }) }; + var contexts = new DefaultMessageContext[10]; + for (var iteration = 0; iteration < 1000; iteration++) + { + for (var i = 0; i < contexts.Length; i++) contexts[i] = consumer.RentContext(message); + await consumer.ProcessBatchAsync(contexts); + for (var i = 0; i < contexts.Length; i++) contexts[i].Dispose(); + using var scope = scopes.CreateScope(); + _ = scope.ServiceProvider.GetRequiredService(); + } + var start = GC.GetAllocatedBytesForCurrentThread(); + for (var iteration = 0; iteration < 1000; iteration++) + { + using var scope = scopes.CreateScope(); + _ = scope.ServiceProvider.GetRequiredService(); + } + var baseline = GC.GetAllocatedBytesForCurrentThread() - start; + start = GC.GetAllocatedBytesForCurrentThread(); + for (var iteration = 0; iteration < 1000; iteration++) + { + for (var i = 0; i < contexts.Length; i++) contexts[i] = consumer.RentContext(message); + await consumer.ProcessBatchAsync(contexts); + for (var i = 0; i < contexts.Length; i++) contexts[i].Dispose(); + } + var composed = GC.GetAllocatedBytesForCurrentThread() - start; + await Assert.That(composed).IsEqualTo(baseline); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Executable_receive_and_generated_batch_share_existing_size_wait_and_scope_declaration(bool native) + { + await using var provider = Provider(size: 3, nativeSize: native ? 10 : 1); + var incoming = Input(3); + var offset = 0; + BatchReceiveDelegate read = (destination, wait, _) => + { + if (wait > Definition(provider).BatchWait) throw new Exception("Wait exceeds declaration"); + incoming.AsMemory(offset, destination.Length).CopyTo(destination); + offset += destination.Length; + return new(destination.Length); + }; + var executor = new BatchReceiveExecutor(provider, "test", Definition(provider), "audit", native ? read : null, native ? null : read); + var storage = new Incoming[executor.MaximumSize]; + var count = await executor.ReceiveAsync(storage); + var output = Sentinels(4); + await Pipeline(provider).ProcessBatchAsync(storage.AsMemory(0, count), output); + await Assert.That(count).IsEqualTo(3); + await Assert.That(provider.GetRequiredService().Scopes.Count).IsEqualTo(1); + await Assert.That(output.Take(3).All(item => item.Kind == DispositionKind.Complete)).IsTrue(); + await Assert.That(output[3].Kind).IsEqualTo(DispositionKind.SettledByHandler); + } + + [Test] + public async Task Handled_batch_failures_mark_error_without_exception_events() + { + await using var provider = Provider(); + using var source = new ActivitySource("Relayer"); + Activity? observed = null; + using var listener = new ActivityListener + { + ShouldListenTo = candidate => ReferenceEquals(candidate, source), + Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded, + ActivityStopped = activity => observed = activity + }; + ActivitySource.AddActivityListener(listener); + provider.GetRequiredService().Invoke = (_, _) => ValueTask.FromException(new ApplicationException("handler")); + await Pipeline(provider, static (_, _, _) => default, source: source).ProcessBatchAsync(Input(3), new Disposition[3]); + await Assert.That(observed!.Status).IsEqualTo(ActivityStatusCode.Error); + await Assert.That(observed.GetTagItem("error.type") as string).IsEqualTo("System.ApplicationException"); + await Assert.That(observed.Events.Count()).IsEqualTo(0); + } + + internal static ServiceProvider Provider(int size = 4, int nativeSize = 10) + { + var services = new ServiceCollection(); + services.AddSingleton(); + services.AddSingleton(new Transport(nativeSize)); + services.AddSingleton(provider => provider.GetRequiredService()); + services.AddSingleton(); + services.AddScoped(); + services.AddSingleton(); + services.AddRelayer(builder => + { + builder.MessageTypes.Add("batch.payload"); + builder.Handler(); + builder.AddTransport("test", transport => + { + transport.Send("destination"); + transport.Consume("source", consumer => consumer.Handler().Batch(size, TimeSpan.FromSeconds(10))); + }); + }); + return services.BuildServiceProvider(new ServiceProviderOptions { ValidateScopes = true }); + } + + internal static IConsumerDefinition Definition(ServiceProvider provider) => provider.GetRequiredService().Transports[0].Consumers[0]; + internal static ConsumePipeline Consumer(ServiceProvider provider, ConsumeFailureDelegate? failure = null, FailurePipeline? failures = null, ActivitySource? source = null) + { + var scopes = provider.GetRequiredService(); + var messages = provider.GetRequiredService(); + var serializer = provider.GetRequiredService(); + var builder = failures is null ? new ConsumePipelineBuilder(scopes, messages, serializer, failure ?? (static (_, error, _) => ValueTask.FromException(error))) + : new ConsumePipelineBuilder(scopes, messages, serializer, failures); + return builder.BuildBatch(provider.GetRequiredService().GetBatchHandler(), Definition(provider), source); + } + private static ReceivePipeline Pipeline(ServiceProvider provider, ConsumeFailureDelegate? failure = null, FailurePipeline? failures = null, ActivitySource? source = null) + => new(Consumer(provider, failure, failures, source), new HeaderNames(), 8); + internal static Incoming[] Input(int count) => Enumerable.Range(0, count).Select(i => new Incoming(i.ToString())).ToArray(); + private static Disposition[] Sentinels(int count) => Enumerable.Repeat(Disposition.SettledByHandler, count).ToArray(); + public sealed class Options; + [Message("batch.payload")] + public sealed class Payload; + public sealed class Control + { + public Func, CancellationToken, ValueTask>? Invoke { get; set; } + public List Scopes { get; } = []; + public int Disposed { get; set; } + public Task? Disposal { get; set; } + public TaskCompletionSource? DisposalStarted { get; set; } + } + public sealed class Lifetime(Control control) : IAsyncDisposable + { + public async ValueTask DisposeAsync() + { + control.DisposalStarted?.TrySetResult(); + if (control.Disposal is { } disposal) await disposal; + control.Disposed++; + } + } + public sealed class Handler(Control control, Lifetime lifetime) : IBatchHandler + { + public ValueTask HandleAsync(Batch batch, CancellationToken cancellationToken) + { + _ = lifetime; + var scope = batch.Items[0].Context.Services; + if (batch.Items.Any(item => !ReferenceEquals(scope, item.Context.Services))) throw new Exception("Scopes differ"); + control.Scopes.Add(scope); + return control.Invoke?.Invoke(batch, cancellationToken) ?? new(BatchResult.Success); + } + } + public sealed class AllocationHandler : IBatchHandler + { + public ValueTask HandleAsync(Batch batch, CancellationToken cancellationToken) => new(BatchResult.Success); + } + internal sealed class Serializer : IMessageSerializer + { + private readonly Payload _payload = new(); + public string ContentType => "test/cached"; + public TMessage Deserialize(ReadOnlySequence source) => source.FirstSpan[0] == 0 ? throw new FormatException() : (TMessage)(object)_payload; + public void Serialize(TMessage message, IBufferWriter destination) { destination.GetSpan(1)[0] = 1; destination.Advance(1); } + } + internal sealed record Incoming(string Id) + { + public string Type { get; init; } = "batch.payload;v=1"; + public byte Value { get; init; } = 1; + } + internal readonly struct Binding : IMessageBinding + { + public static ReadOnlySequence GetBody(Incoming message) => new(new[] { message.Value }); + public static int? GetDeliveryCount(Incoming message) => 1; + public static bool TryGetHeader(Incoming message, string name, out WireString value) + { + value = name switch { "ce_id" => new(message.Id), "ce_type" => new(message.Type), "traceparent" => new("00-11111111111111111111111111111111-2222222222222222-01"), _ => default }; + return !value.IsEmpty; + } + } + internal sealed class Transport(int nativeSize) : ITransport + { + public string Name => "test"; + public int Reads { get; private set; } + public int Sends { get; private set; } + public bool NativeDeadLetter { get; set; } = true; + public Func? Send { get; set; } + public TransportCapabilities GetCapabilities(string endpoint) { Reads++; return new() { DeadLetter = NativeDeadLetter, MaxBatchSize = nativeSize }; } + public ValueTask SendAsync(OutgoingMessage message, CancellationToken cancellationToken) { Sends++; return Send?.Invoke(message, cancellationToken) ?? default; } + public ValueTask SendBatchAsync(ReadOnlyMemory messages, CancellationToken cancellationToken) => throw new NotSupportedException(); + public ValueTask ApplyTopologyAsync(TopologyMode mode, CancellationToken cancellationToken) => new(new TopologyReport([])); + public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public ValueTask DisposeAsync() => default; + } +} diff --git a/tests/Relayer.Tests/BatchReceiveExecutorTests.cs b/tests/Relayer.Tests/BatchReceiveExecutorTests.cs new file mode 100644 index 000000000..e65ee6928 --- /dev/null +++ b/tests/Relayer.Tests/BatchReceiveExecutorTests.cs @@ -0,0 +1,136 @@ +using Microsoft.Extensions.DependencyInjection; + +namespace Relayer.Tests; + +public class BatchReceiveExecutorTests +{ + [Test] + [Arguments(9, 10, 9)] + [Arguments(10, 10, 10)] + [Arguments(11, 10, 10)] + public async Task Native_selection_caps_exact_count_boundary_and_uses_configured_wait(int configured, int nativeLimit, int expected) + { + await using var provider = BatchPipelineTests.Provider(configured, nativeLimit); + var calls = 0; + var executor = new BatchReceiveExecutor(provider, "test", BatchPipelineTests.Definition(provider), "audit", + (destination, wait, _) => + { + calls++; + if (destination.Length != expected || wait != TimeSpan.FromSeconds(10)) throw new Exception("Configuration not honored"); + destination.Span.Fill(42); + return new(expected - 1); // a native byte limit may produce fewer messages + }, (_, _, _) => throw new Exception("Native batching must take precedence")); + var output = new int[expected + 1]; + var count = await executor.ReceiveAsync(output); + await Assert.That(executor.UsesNativeBatching).IsTrue(); + await Assert.That(executor.MaximumSize).IsEqualTo(expected); + await Assert.That(count).IsEqualTo(expected - 1); + await Assert.That(output[^1]).IsEqualTo(0); + await executor.ReceiveAsync(output); + await Assert.That(calls).IsEqualTo(2); + await Assert.That(provider.GetRequiredService().Reads).IsEqualTo(1); + } + + [Test] + [Arguments(1, true)] + [Arguments(10, false)] + public async Task Fallback_requires_single_executor_when_native_capability_or_executor_is_absent(int nativeLimit, bool offerNative) + { + await using var provider = BatchPipelineTests.Provider(3, nativeLimit); + var calls = 0; + var executor = new BatchReceiveExecutor(provider, "test", BatchPipelineTests.Definition(provider), "audit", + offerNative ? (_, _, _) => throw new Exception("Capability alone cannot select native batching") : null, + (destination, _, _) => + { + if (destination.Length != 1) throw new Exception("Single receiver must receive one slot"); + destination.Span[0] = ++calls; + return new(1); + }); + var output = new int[4]; + await Assert.That(await executor.ReceiveAsync(output)).IsEqualTo(3); + await Assert.That(executor.UsesNativeBatching).IsFalse(); + await Assert.That(string.Join(",", output)).IsEqualTo("1,2,3,0"); + } + + [Test] + public async Task Partial_batch_wait_starts_at_first_delivery_and_deadline_is_not_reset_per_item() + { + await using var provider = BatchPipelineTests.Provider(4, 1); + var clock = new ManualTime(); + var waits = new List(); + var executor = new BatchReceiveExecutor(provider, "test", BatchPipelineTests.Definition(provider), "audit", singleReceive: + (destination, wait, _) => + { + waits.Add(wait); + destination.Span[0] = waits.Count; + clock.Advance(waits.Count == 1 ? TimeSpan.FromSeconds(50) : TimeSpan.FromSeconds(Math.Min(6, wait.TotalSeconds))); + return new(1); + }, timeProvider: clock); + var output = new int[4]; + await Assert.That(await executor.ReceiveAsync(output)).IsEqualTo(3); + await Assert.That(string.Join(",", waits.Select(wait => wait.TotalSeconds))).IsEqualTo("10,10,4"); + await Assert.That(output[^1]).IsEqualTo(0); + } + + [Test] + public async Task Receive_timeout_returns_partial_or_empty_batch_without_pending_background_reads() + { + await using var provider = BatchPipelineTests.Provider(4, 1); + var calls = 0; + var executor = new BatchReceiveExecutor(provider, "test", BatchPipelineTests.Definition(provider), "audit", singleReceive: + (destination, _, _) => { calls++; if (calls == 1) { destination.Span[0] = 42; return new(1); } return new(0); }); + var output = new int[4]; + await Assert.That(await executor.ReceiveAsync(output)).IsEqualTo(1); + await Assert.That(calls).IsEqualTo(2); + await Assert.That(await executor.ReceiveAsync(output)).IsEqualTo(0); + await Assert.That(calls).IsEqualTo(3); + } + + [Test] + [Arguments(1)] + [Arguments(10)] + public async Task Startup_rejects_declaration_without_executable_path_with_consumer_context(int nativeLimit) + { + await using var provider = BatchPipelineTests.Provider(4, nativeLimit); + await Assert.That(() => new BatchReceiveExecutor(provider, "test", BatchPipelineTests.Definition(provider), "audit")) + .Throws().WithMessageContaining("Consumer 'audit' from 'source' on transport 'test'"); + if (nativeLimit == 1) + await Assert.That(() => new BatchReceiveExecutor(provider, "test", BatchPipelineTests.Definition(provider), "audit", (_, _, _) => new(1))) + .Throws().WithMessageContaining("has no executor"); + } + + [Test] + [Arguments(-1)] + [Arguments(2)] + public async Task Invalid_executor_counts_propagate_without_returning_success(int count) + { + await using var provider = BatchPipelineTests.Provider(3, 1); + var executor = new BatchReceiveExecutor(provider, "test", BatchPipelineTests.Definition(provider), "audit", singleReceive: (_, _, _) => new(count)); + await Assert.That(async () => await executor.ReceiveAsync(new int[3])).Throws(); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Receive_cancellation_is_observed_before_and_after_native_work(bool native) + { + await using var provider = BatchPipelineTests.Provider(3); + using var cancellation = new CancellationTokenSource(); + var calls = 0; + BatchReceiveDelegate receive = (_, _, _) => { calls++; cancellation.Cancel(); return new(1); }; + var executor = new BatchReceiveExecutor(provider, "test", BatchPipelineTests.Definition(provider), "audit", + native ? receive : null, native ? null : receive); + await Assert.That(async () => await executor.ReceiveAsync(new int[3], cancellation.Token)).Throws(); + await Assert.That(calls).IsEqualTo(1); + await Assert.That(async () => await executor.ReceiveAsync(new int[3], cancellation.Token)).Throws(); + await Assert.That(calls).IsEqualTo(1); + } + + private sealed class ManualTime : TimeProvider + { + private long _timestamp; + public override long TimestampFrequency => TimeSpan.TicksPerSecond; + public override long GetTimestamp() => _timestamp; + internal void Advance(TimeSpan elapsed) => _timestamp += elapsed.Ticks; + } +} diff --git a/website/docs/guides/configuration.md b/website/docs/guides/configuration.md index 23975a329..b00d4052c 100644 --- a/website/docs/guides/configuration.md +++ b/website/docs/guides/configuration.md @@ -41,6 +41,13 @@ Transport names are case-sensitive and unique across all transport kinds. Severa `Concurrency` defaults to 1. `BatchSize` defaults to 1, which disables batching; `BatchWait` defaults to 100 ms. Transports honor these with native behavior and the core scheduler where applicable, and validate their native limits before starting. Declaring them never installs an emulated batching or ordering feature. +The core's [batch receive executor](../transports/consume-pipeline.md#batch-consumers) +uses native receive batching when both its executor and endpoint capability exist, +capped by `min(BatchSize, MaxBatchSize)`. Otherwise an individual receive executor +supplies core accumulation up to `BatchSize`, with one partial-batch deadline from +the first delivery. Native byte limits remain authoritative. Missing executors +fail composition before receives start with consumer, source, and transport context. + ## Startup and reload diff --git a/website/docs/guides/handlers.md b/website/docs/guides/handlers.md index 344c2911e..9896c8cd1 100644 --- a/website/docs/guides/handlers.md +++ b/website/docs/guides/handlers.md @@ -38,6 +38,24 @@ public sealed class AuditHandler(AuditStore store) : IBatchHandler Return `BatchResult.Success` when every message succeeded. +Configure the existing consumer declaration with `.Batch(maxSize, maxWait)`. +The core composes generated batch dispatch in one fresh scope per batch attempt. +Only failed items are retried; an exception from the handler fails every item in +that invocation. Success waits for asynchronous scope disposal and durable work +before the adapter receives settlement decisions. + +Direct sends from the scoped `ISender` are buffered until the entire attempt +succeeds. A partial failure with buffered sends fails the receive call because +those sends cannot be attributed to individual items. Use explicit per-message +durable outbox transactions when partial success also produces messages. Do not +retain the borrowed batch or its item contexts after handler completion. + +Adapters must install a native or core client-side receive executor before +starting consumers; declaring a size does not supply one. The core execution +seam is available now; the in-memory hosted adapter still explicitly rejects +batch-handler composition. See [batch composition](../transports/consume-pipeline.md#batch-consumers) +for transport-author integration and native count/wait limits. + ## Registration without scanning Relayer never scans assemblies at runtime. Register handlers inside `AddRelayer`: diff --git a/website/docs/roadmap.md b/website/docs/roadmap.md index fc65c83f9..99f3b0154 100644 --- a/website/docs/roadmap.md +++ b/website/docs/roadmap.md @@ -12,6 +12,7 @@ Relayer is in early development. Track progress in [GitHub issues](https://githu - Compile-time analyzers and a code fix ([diagnostics](reference/diagnostics.md)). - The scoped send pipeline, send middleware and outbox enlistment hooks. - The consume pipeline and the native receive SPI. +- Generated batch handler execution, durable partial-failure decisions, and validated native/client-side receive executors for transport authors. - Typed failure classification, in-process retries, delayed redelivery and dead-letter copies with error history. - Declared topology with validate and provision modes, and JSON export. - The [in-memory transport](transports/in-memory.md), with native queue and partitioned log semantics. diff --git a/website/docs/transports/consume-pipeline.md b/website/docs/transports/consume-pipeline.md index 3e65bd89a..7a2ec475c 100644 --- a/website/docs/transports/consume-pipeline.md +++ b/website/docs/transports/consume-pipeline.md @@ -98,3 +98,82 @@ a real native client, or its total receive allocation goal. Those require the transport and CI regression suites tracked in [#19](https://github.com/thomhurst/Relayer/issues/19). Pending asynchronous operations use a pooled `ValueTask` state machine in the execution layer; custom middleware and user handlers retain responsibility for their own asynchronous allocations. + +## Batch consumers + +Configure the user call site with the same `Batch(maxSize, maxWait)` declaration: + +```csharp +transport.Consume("audit", consumer => consumer + .Handler() + .Batch(maxSize: 10, maxWait: TimeSpan.FromMilliseconds(20))); +``` + +The transport composes one homogeneous batch handler at startup. Select its generated +`BatchHandlerDescriptor` once; do not use reflection to find its message contract. +Pass the existing `IConsumerDefinition` to `BuildBatch` and `BatchReceiveExecutor`: + +```csharp +var execution = new ConsumePipelineBuilder(scopeFactory, messageTypes, serializer, failurePipeline) + .BuildBatch(handlers.GetBatchHandler(), definition, + activitySource: relayerActivitySource); +var receive = new ReceivePipeline(execution, headerNames, + contextPoolCapacity: definition.BatchSize * definition.Concurrency); +var executor = new BatchReceiveExecutor(services, transportName, definition, + consumerName, nativeReceive: nativeBatchReceive, singleReceive: nativeSingleReceive); + +// Inside the native receive loop; storage belongs to this loop until settlement finishes. +var count = await executor.ReceiveAsync(deliveries, cancellationToken).ConfigureAwait(false); +await receive.ProcessBatchAsync(deliveries[..count], dispositions[..count], cancellationToken) + .ConfigureAwait(false); +// Only now apply dispositions[..count] through the native client's settlement API. +``` + +`BuildBatch` uses one fresh async scope per batch attempt. It rejects mixing +single-message middleware, dispatch, endpoint telemetry, or settlement callbacks into +that composition. Record endpoint metrics and settle native deliveries around the +batch call; these single-message callbacks are not silently ignored. +Message types not handled by that batch consumer enter failure handling individually. +Invalid bodies also enter failure handling individually; the handler sees only decoded +items, so partial-failure indexes refer to the batch actually passed to the handler. +A thrown handler exception fails every item passed to that invocation. Invalid result +indexes or null exceptions fail that invocation rather than losing a failure. +The executable `FailurePipeline` retries only failed items, in a fresh scope, then +produces durable per-message redelivery or dead-letter decisions. The explicit failure +delegate remains available to transport integrations that own durable failure handling. + +Successful results wait for asynchronous scope disposal and buffered sends. Failed +attempts discard their buffered direct sends. A partially failed attempt with buffered +sends fails the entire receive call: one scoped sender cannot attribute those sends +to individual messages. Use explicit per-message durable outbox transactions when +partial success also produces messages (D28). Failure handling and disposal errors +propagate without publishing any batch dispositions. + +Pass the application's shared `Relayer` ActivitySource to `BuildBatch` to trace one +`process {source}` CONSUMER span for the batch, including retries. It links each valid +creation context and uses only the ambient span as parent. It includes +`messaging.batch.message_count`. The caller owns the source; no process-wide source +or second source owner is created. This is the batch execution seam for #13's shared +tracing integration. Native settlement and its tracing remain the adapter's work. +Do not retain the borrowed `Batch.Items`, message contexts, or native features after +handler completion. Pools retain bounded reusable storage sized by the declaration's +batch size and concurrency; overflow is temporary. + +`BatchReceiveExecutor` resolves cached endpoint capabilities once during construction. +When a native executor exists and `MaxBatchSize` permits native batching, it uses that +executor with `min(BatchSize, MaxBatchSize)` slots and `BatchWait`. Native byte limits +can yield a smaller batch. Otherwise it requires an individual receive executor and +accumulates one delivery at a time, preserving delivery order. The partial-batch +deadline starts with the first delivery and never resets after later deliveries. +Each receive delegate must honor the supplied wait and cancellation, returning zero +on timeout. No background receives are left running. A declaration without either +usable executor fails construction with transport, source, consumer, and remedy. +Adapters must construct the executor before starting their receive services. +On receive exceptions, the caller still owns any deliveries already written into its +buffer and uses native shutdown/redelivery to release them; it must not acknowledge +them as successful. No broker or transport settlement behavior is emulated. + +The `BatchConsumePipelineBenchmarks` comparison reports per-batch allocations against +matching fresh DI scope, scoped sender, cached serializer, and generated dispatch. +It does not establish the end-to-end native-client throughput budget; #19 owns that +transport regression measurement. diff --git a/website/docs/transports/receive.md b/website/docs/transports/receive.md index dbc72bdb3..303387ab2 100644 --- a/website/docs/transports/receive.md +++ b/website/docs/transports/receive.md @@ -33,4 +33,4 @@ The native feature's `Disposition` starts as `Complete`. A failure delegate sets `ProcessAsync` returns only after handler work, failure handling, and async scope disposal succeed. Exceptions and cancellation propagate without returning a disposition. The native receive loop applies its ordinary failure behavior in that case. -`ProcessBatchAsync(ReadOnlyMemory, Memory, cancellationToken)` processes deliveries in input order and writes one decision per message. It adapts a native receive batch to single-message consume dispatch; it does not compose an `IBatchHandler`. Output must have at least as many slots as input; an unused tail stays unchanged. Settle from the output only after the entire call succeeds. A failed call may have completed durable work for earlier messages, so redelivery remains at-least-once. Input and output storage must remain valid and unchanged until the call completes. +`ProcessBatchAsync(ReadOnlyMemory, Memory, cancellationToken)` processes deliveries in input order and writes one decision per message. With `BuildBatch`, it invokes the generated `IBatchHandler` once per batch attempt in one scope and publishes all output only after durable work succeeds. Otherwise it adapts the native batch to single-message consume dispatch. See [batch composition](consume-pipeline.md#batch-consumers) for executor selection, size/wait limits, partial failures, and lifetime rules. Output must have at least as many slots as input; an unused tail stays unchanged. Settle from the output only after the entire call succeeds. A failed call may have completed durable work for earlier messages, so redelivery remains at-least-once. Input and output storage must remain valid and unchanged until the call completes. diff --git a/website/src/pages/index.js b/website/src/pages/index.js index 19f39bc07..1974b1ebe 100644 --- a/website/src/pages/index.js +++ b/website/src/pages/index.js @@ -273,6 +273,7 @@ function CallSite() { const status = [ ['Configuration, routes and startup validation', 'Implemented', true], ['Source-generated handlers, messages and JSON', 'Implemented', true], + ['Batch dispatch and receive executor composition', 'Implemented core seam', true], ['Send pipeline and middleware', 'Implemented', true], ['Consume pipeline and receive SPI', 'Implemented', true], ['Failure classification, retries and dead-letter copies', 'Implemented', true], From e630d38651ed3a70e8c5e847dacbbb15021b67b1 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:35:49 +0000 Subject: [PATCH 2/5] fix: bound batch failure handling and reuse tracing storage (#11) --- .../BatchConsumePipelineBenchmarks.cs | 57 ++++++++++- docs/decisions.md | 13 ++- src/Relayer/Handling/Batch.cs | 4 +- src/Relayer/Pipeline/BatchExecution.cs | 37 ++++--- tests/Relayer.Tests/BatchPipelineTests.cs | 46 +++++++-- .../BatchTracingTests.cs | 99 +++++++++++++++++++ .../Relayer.Tracing.Tests.csproj | 2 + website/docs/guides/handlers.md | 11 ++- website/docs/transports/consume-pipeline.md | 6 +- 9 files changed, 240 insertions(+), 35 deletions(-) create mode 100644 tests/Relayer.Tracing.Tests/BatchTracingTests.cs diff --git a/benchmarks/Relayer.Benchmarks/BatchConsumePipelineBenchmarks.cs b/benchmarks/Relayer.Benchmarks/BatchConsumePipelineBenchmarks.cs index 6ca37ca16..204628d64 100644 --- a/benchmarks/Relayer.Benchmarks/BatchConsumePipelineBenchmarks.cs +++ b/benchmarks/Relayer.Benchmarks/BatchConsumePipelineBenchmarks.cs @@ -1,4 +1,5 @@ using System.Buffers; +using System.Diagnostics; using BenchmarkDotNet.Attributes; using Microsoft.Extensions.DependencyInjection; using Relayer.Serialization; @@ -19,10 +20,18 @@ public class BatchConsumePipelineBenchmarks private Batch _directBatch = null!; private ConsumeMessage _message; private DefaultMessageContext[] _contexts = null!; + private ActivitySource _source = null!; + private ActivityListener _listener = null!; + private Activity _ambient = null!; + private ActivityLink[] _links = null!; + private KeyValuePair[] _tags = null!; [Params(1, 10, 100)] public int BatchSize { get; set; } + [Params(false, true)] + public bool DropTracing { get; set; } + [GlobalSetup] public void Setup() { @@ -39,9 +48,24 @@ public void Setup() _scopes = _provider.GetRequiredService(); _descriptor = _provider.GetRequiredService().GetBatchHandler(); var definition = _provider.GetRequiredService().Transports[0].Consumers[0]; + _source = new ActivitySource("Relayer"); + _listener = new ActivityListener + { + ShouldListenTo = source => DropTracing && ReferenceEquals(source, _source), + Sample = static (ref ActivityCreationOptions _) => ActivitySamplingResult.None + }; + ActivitySource.AddActivityListener(_listener); + _ambient = new Activity("request").Start(); + _links = new ActivityLink[BatchSize]; + _tags = + [ + new("messaging.operation.type", "process"), new("messaging.operation.name", "process"), + new("messaging.destination.name", "source"), new("messaging.batch.message_count", BatchSize) + ]; _pipeline = new ConsumePipelineBuilder(_scopes, _provider.GetRequiredService(), _serializer, - static (_, error, _) => ValueTask.FromException(error)).BuildBatch(_descriptor, definition); - _message = new() { MessageId = "benchmark", MessageType = new("benchmark.batch", 1), Body = ReadOnlySequence.Empty }; + static (_, error, _) => ValueTask.FromException(error)).BuildBatch(_descriptor, definition, _source); + _message = new() { MessageId = "benchmark", MessageType = new("benchmark.batch", 1), Body = ReadOnlySequence.Empty, + Headers = DropTracing ? new TraceHeaders() : null }; _contexts = new DefaultMessageContext[BatchSize]; var items = new BatchItem[BatchSize]; for (var i = 0; i < items.Length; i++) items[i] = new(_serializer.Deserialize(_message.Body), _directContext); @@ -51,6 +75,7 @@ public void Setup() [Benchmark(Baseline = true)] public async ValueTask DirectScopedBatch() { + using var activity = StartDirectActivity(); var scope = new AsyncServiceScope(_scopes.CreateScope()); try { @@ -62,6 +87,17 @@ public async ValueTask DirectScopedBatch() finally { await scope.DisposeAsync().ConfigureAwait(false); } } + private Activity? StartDirectActivity() + { + if (!DropTracing) return null; + for (var i = 0; i < BatchSize; i++) + { + ActivityContext.TryParse(TraceHeaders.Parent, null, true, out var context); + _links[i] = new(context); + } + return _source.StartActivity("process source", ActivityKind.Consumer, Activity.Current?.Context ?? default, _tags, _links); + } + [Benchmark] public async ValueTask ComposedBatch() { @@ -74,7 +110,13 @@ public async ValueTask ComposedBatch() } [GlobalCleanup] - public void Cleanup() => _provider.Dispose(); + public void Cleanup() + { + _ambient.Dispose(); + _listener.Dispose(); + _source.Dispose(); + _provider.Dispose(); + } public sealed class Options; [Message("benchmark.batch")] public sealed class Payload { public int Value => 42; } @@ -96,6 +138,15 @@ private sealed class Serializer : IMessageSerializer public TMessage Deserialize(ReadOnlySequence source) => (TMessage)(object)_payload; public void Serialize(TMessage message, IBufferWriter destination) => throw new NotSupportedException(); } + private sealed class TraceHeaders : MessageHeaders + { + internal const string Parent = "00-11111111111111111111111111111111-2222222222222222-01"; + public override bool TryGetValue(string name, out WireString value) + { + value = name == "traceparent" ? new(Parent) : default; + return !value.IsEmpty; + } + } private sealed class DirectContext : MessageContext { public IServiceProvider Provider { get; set; } = null!; diff --git a/docs/decisions.md b/docs/decisions.md index 9faf60fc9..6486620f9 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -419,12 +419,15 @@ successful or failed batch item without a second, implicit message context. **Decision.** - Compose a homogeneous generated batch handler with the consumer's existing size, wait, and concurrency declaration. Each batch attempt uses one fresh async DI scope. -- Retry only failed items. Dispose the attempt's scope before final failure work, +- Retry only failed items unless unattributed buffered sends fail the whole attempt. + Dispose the attempt's scope before final failure work, direct-send flush, or publication of settlement decisions. - Buffer direct sends for the attempt. Flush only a wholly successful attempt; discard a wholly failed attempt's buffer. If partial success has buffered direct - sends, fail the receive call without publishing dispositions. Do not guess which - item produced a send or silently lose successful items' sends. + sends, discard the buffer and route every item through the normal failure policy. + This bounds poison-message attempts through configured retry, redelivery and + dead-letter handling. Do not guess which item produced a send or settle an item + successfully after discarding its sends. - Handlers that need partial success with outgoing messages use explicit durable per-message outbox transactions. At-least-once native redelivery still applies if later failure work or scope disposal fails. @@ -432,6 +435,8 @@ successful or failed batch item without a second, implicit message context. receives start. Declaring a capability or batch size never supplies an executor. **Consequences.** Successful deliveries never settle before scope disposal and all -required durable work. A failed batch call can repeat already durable work on native +required durable work. Partial failure with buffered sends can retry or dead-letter +otherwise successful items; use per-message outbox transactions for independent +outcomes with outgoing messages. A failed batch call can repeat already durable work on native redelivery, as expected for at-least-once delivery. The core does not invent native settlement or per-message ambient sender semantics. diff --git a/src/Relayer/Handling/Batch.cs b/src/Relayer/Handling/Batch.cs index 98c48a7fb..f3df8b295 100644 --- a/src/Relayer/Handling/Batch.cs +++ b/src/Relayer/Handling/Batch.cs @@ -3,6 +3,7 @@ namespace Relayer; /// A batch of messages delivered to an . /// The message type. /// The messages and their contexts, in delivery order. +/// The batch, its items and contexts are borrowed only for the handler call. Do not retain them after returning. public sealed record Batch(IReadOnlyList> Items) { /// The number of messages in the batch. @@ -23,7 +24,8 @@ public sealed class BatchResult /// Every message succeeded. public static BatchResult Success { get; } = new(new Dictionary()); - /// Failures keyed by index within the batch. Only these messages enter the failure pipeline. + /// Failures keyed by index within the batch. These messages enter the failure pipeline. + /// A partial failure with buffered direct sends fails the whole attempt because sends cannot be attributed to individual items. public IReadOnlyDictionary Failures { get; } /// Reports that the messages at the given indexes failed. diff --git a/src/Relayer/Pipeline/BatchExecution.cs b/src/Relayer/Pipeline/BatchExecution.cs index 4ca94cff2..d605d1aee 100644 --- a/src/Relayer/Pipeline/BatchExecution.cs +++ b/src/Relayer/Pipeline/BatchExecution.cs @@ -15,6 +15,7 @@ internal sealed class BatchExecution private readonly ActivitySource? _source; private readonly string _spanName; private readonly string _destination; + private readonly KeyValuePair[] _batchCountTags; private readonly State?[] _states; internal int Size { get; } @@ -32,8 +33,10 @@ internal BatchExecution(IServiceScopeFactory scopes, BatchDispatcher dispatch, M Size = consumer.BatchSize; _destination = consumer.Source; _spanName = "process " + consumer.Source; + _batchCountTags = new KeyValuePair[Size]; + for (var i = 0; i < Size; i++) _batchCountTags[i] = new("messaging.batch.message_count", i + 1); _states = new State[consumer.Concurrency]; - for (var i = 0; i < _states.Length; i++) _states[i] = new State(Size); + for (var i = 0; i < _states.Length; i++) _states[i] = new State(Size, _destination); } [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] @@ -98,7 +101,12 @@ internal async ValueTask ProcessAsync(ConsumePipeline owner, ReadOnlyMemory contexts, State state) { if (_source is null || !_source.HasListeners()) return null; - var count = 0; for (var i = 0; i < contexts.Length; i++) { var headers = contexts.Span[i].Headers; @@ -176,29 +183,31 @@ private static void RecordError(Activity? activity, Exception error) { var traceState = headers.TryGetValue("tracestate", out var value) ? value.ToString() : null; if (ActivityContext.TryParse(parent.ToString(), traceState, true, out var creation)) - state.Links[count++] = new(creation); + state.Links.Add(new(creation)); } } - var tags = new ActivityTagsCollection - { - { "messaging.operation.type", "process" }, { "messaging.operation.name", "process" }, - { "messaging.destination.name", _destination }, { "messaging.batch.message_count", contexts.Length } - }; + state.Tags[^1] = _batchCountTags[contexts.Length - 1]; + // ActivitySource consumes these reusable sampling inputs synchronously. return _source.StartActivity(_spanName, ActivityKind.Consumer, Activity.Current?.Context ?? default, - tags, new ArraySegment(state.Links, 0, count)); + state.Tags, state.Links); } private State Rent() { for (var i = 0; i < _states.Length; i++) if (Interlocked.Exchange(ref _states[i], null) is { } state) return state; - return new State(Size); + return new State(Size, _destination); } - private sealed class State(int size) + private sealed class State(int size, string destination) { internal readonly DefaultMessageContext[] Active = new DefaultMessageContext[size]; internal readonly Exception?[] Errors = new Exception[size]; - internal readonly ActivityLink[] Links = new ActivityLink[size]; + internal readonly List Links = new(size); + internal readonly KeyValuePair[] Tags = + [ + new("messaging.operation.type", "process"), new("messaging.operation.name", "process"), + new("messaging.destination.name", destination), default + ]; } } diff --git a/tests/Relayer.Tests/BatchPipelineTests.cs b/tests/Relayer.Tests/BatchPipelineTests.cs index 811160124..136b9a13d 100644 --- a/tests/Relayer.Tests/BatchPipelineTests.cs +++ b/tests/Relayer.Tests/BatchPipelineTests.cs @@ -201,10 +201,16 @@ public async Task Batch_span_links_every_creation_context_and_uses_only_ambient_ await using var provider = Provider(); using var source = new ActivitySource("Relayer"); Activity? observed = null; + var sampledCount = 0; using var listener = new ActivityListener { ShouldListenTo = candidate => ReferenceEquals(candidate, source), - Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded, + Sample = (ref ActivityCreationOptions options) => + { + foreach (var tag in options.Tags!) + if (tag.Key == "messaging.batch.message_count") sampledCount = (int)tag.Value!; + return ActivitySamplingResult.AllDataAndRecorded; + }, ActivityStopped = activity => observed = activity }; ActivitySource.AddActivityListener(listener); @@ -212,7 +218,8 @@ public async Task Batch_span_links_every_creation_context_and_uses_only_ambient_ var expectedActivity = Activity.Current; var expectedParent = expectedActivity?.Context ?? default; var input = Input(3); - await Pipeline(provider, source: source).ProcessBatchAsync(input, new Disposition[3]); + var pipeline = Pipeline(provider, source: source); + await pipeline.ProcessBatchAsync(input, new Disposition[3]); await Assert.That(observed!.DisplayName).IsEqualTo("process source"); await Assert.That(observed.Kind).IsEqualTo(ActivityKind.Consumer); await Assert.That(observed.ParentSpanId).IsEqualTo(expectedParent.SpanId); @@ -220,7 +227,12 @@ public async Task Batch_span_links_every_creation_context_and_uses_only_ambient_ await Assert.That(observed.GetTagItem("messaging.operation.type") as string).IsEqualTo("process"); await Assert.That(observed.Links.Count()).IsEqualTo(3); await Assert.That(observed.Links.All(link => link.Context.IsRemote)).IsTrue(); + await Assert.That(sampledCount).IsEqualTo(3); await Assert.That(Activity.Current).IsSameReferenceAs(expectedActivity); + await pipeline.ProcessBatchAsync(input.AsMemory(0, 1), new Disposition[1]); + await Assert.That(sampledCount).IsEqualTo(1); + await Assert.That((int)observed!.GetTagItem("messaging.batch.message_count")!).IsEqualTo(1); + await Assert.That(observed.Links.Count()).IsEqualTo(1); } [Test] @@ -250,15 +262,35 @@ public async Task Buffered_sends_flush_only_after_whole_batch_success_and_dispos await Pipeline(provider).ProcessBatchAsync(Input(3), new Disposition[3]); await Assert.That(transport.Sends).IsEqualTo(1); await Assert.That(control.Disposed).IsEqualTo(1); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Partial_failure_with_buffered_sends_retries_whole_attempt_and_reaches_bounded_settlement(bool poison) + { + await using var provider = Provider(); + var control = provider.GetRequiredService(); + var transport = provider.GetRequiredService(); + var calls = 0; + var attempts = new List(); control.Invoke = async (batch, _) => { - await batch.Items[0].Context.Services.GetRequiredService().SendNowAsync(new Payload()); - return BatchResult.PartialFailure(new Dictionary { [1] = new Exception("partial") }); + calls++; + attempts.Add(string.Join(",", batch.Items.Select(item => item.Context.MessageId + ":" + item.Context.Attempt))); + for (var i = 0; i < batch.Count; i++) + await batch.Items[i].Context.Services.GetRequiredService().SendNowAsync(new Payload()); + return poison || calls == 1 + ? BatchResult.PartialFailure(new Dictionary { [1] = new Exception("partial") }) + : BatchResult.Success; }; + var failures = new FailurePipeline(provider, "test", "source", "batch", new() { RetryDelays = new[] { TimeSpan.Zero }, Jitter = 0 }); var output = Sentinels(3); - await Assert.That(async () => await Pipeline(provider).ProcessBatchAsync(Input(3), output)).Throws(); - await Assert.That(transport.Sends).IsEqualTo(1); - await Assert.That(output.All(item => item.Kind == DispositionKind.SettledByHandler)).IsTrue(); + await Pipeline(provider, failures: failures).ProcessBatchAsync(Input(3), output); + await Assert.That(string.Join(";", attempts)).IsEqualTo("0:1,1:1,2:1;0:2,1:2,2:2"); + await Assert.That(output.All(item => item.Kind == (poison ? DispositionKind.DeadLetter : DispositionKind.Complete))).IsTrue(); + await Assert.That(transport.Sends).IsEqualTo(poison ? 0 : 3); + await Assert.That(control.Disposed).IsEqualTo(2); } [Test] diff --git a/tests/Relayer.Tracing.Tests/BatchTracingTests.cs b/tests/Relayer.Tracing.Tests/BatchTracingTests.cs new file mode 100644 index 000000000..f1b23f39f --- /dev/null +++ b/tests/Relayer.Tracing.Tests/BatchTracingTests.cs @@ -0,0 +1,99 @@ +using System.Buffers; +using System.Diagnostics; +using Microsoft.Extensions.DependencyInjection; +using Relayer.Serialization; + +namespace Relayer.Tests; + +public class BatchTracingTests +{ + [Test] + [Arguments(1, false)] + [Arguments(1, true)] + [Arguments(10, false)] + [Arguments(10, true)] + public async Task Dropped_batch_spans_add_no_allocations_beyond_scope_and_framework_context_parsing(int size, bool links) + { + var services = new ServiceCollection(); + services.AddSingleton(); + services.AddSingleton(); + services.AddRelayer(builder => + { + builder.MessageTypes.Add("batch.tracing"); + builder.AddTransport("test", transport => + transport.Consume("source", consumer => consumer.Handler().Batch(size, TimeSpan.FromSeconds(1)))); + }); + await using var provider = services.BuildServiceProvider(); + var scopes = provider.GetRequiredService(); + using var source = new ActivitySource("Relayer"); + using var listener = new ActivityListener + { + ShouldListenTo = candidate => ReferenceEquals(candidate, source), + Sample = static (ref ActivityCreationOptions _) => ActivitySamplingResult.None + }; + ActivitySource.AddActivityListener(listener); + // Match ActivitySource's ambient context and exclude its root trace ID allocation. + using var ambient = new Activity("request").Start(); + var consumer = new ConsumePipelineBuilder(scopes, provider.GetRequiredService(), + provider.GetRequiredService(), static (_, error, _) => ValueTask.FromException(error)) + .BuildBatch(provider.GetRequiredService().GetBatchHandler(), + provider.GetRequiredService().Transports[0].Consumers[0], source); + var message = new ConsumeMessage + { + MessageId = "allocation", MessageType = new("batch.tracing", 1), Body = ReadOnlySequence.Empty, + Headers = links ? new TraceHeaders() : null + }; + var contexts = new DefaultMessageContext[size]; + for (var iteration = 0; iteration < 1000; iteration++) + { + for (var i = 0; i < size; i++) contexts[i] = consumer.RentContext(message); + await consumer.ProcessBatchAsync(contexts); + for (var i = 0; i < size; i++) contexts[i].Dispose(); + Baseline(); + } + var start = GC.GetAllocatedBytesForCurrentThread(); + for (var iteration = 0; iteration < 1000; iteration++) Baseline(); + var baseline = GC.GetAllocatedBytesForCurrentThread() - start; + start = GC.GetAllocatedBytesForCurrentThread(); + for (var iteration = 0; iteration < 1000; iteration++) + { + for (var i = 0; i < size; i++) contexts[i] = consumer.RentContext(message); + await consumer.ProcessBatchAsync(contexts); + for (var i = 0; i < size; i++) contexts[i].Dispose(); + } + var composed = GC.GetAllocatedBytesForCurrentThread() - start; + await Assert.That(composed).IsEqualTo(baseline); + + void Baseline() + { + using var scope = scopes.CreateScope(); + _ = scope.ServiceProvider.GetRequiredService(); + if (links) + for (var i = 0; i < size; i++) ActivityContext.TryParse(TraceHeaders.Parent, null, true, out _); + } + } + + public sealed class Options; + [Message("batch.tracing")] + public sealed class Payload; + public sealed class Handler : IBatchHandler + { + public ValueTask HandleAsync(Batch batch, CancellationToken cancellationToken) => new(BatchResult.Success); + } + private sealed class Serializer : IMessageSerializer + { + private readonly Payload _payload = new(); + public string ContentType => "test/cached"; + public TMessage Deserialize(ReadOnlySequence source) => (TMessage)(object)_payload; + public void Serialize(TMessage message, IBufferWriter destination) => throw new NotSupportedException(); + } + private sealed class TraceHeaders : MessageHeaders + { + internal const string Parent = "00-11111111111111111111111111111111-2222222222222222-01"; + public override bool TryGetValue(string name, out WireString value) + { + value = name == "traceparent" ? new(Parent) : default; + return !value.IsEmpty; + } + } +} diff --git a/tests/Relayer.Tracing.Tests/Relayer.Tracing.Tests.csproj b/tests/Relayer.Tracing.Tests/Relayer.Tracing.Tests.csproj index 45e70f0ab..f6812e621 100644 --- a/tests/Relayer.Tracing.Tests/Relayer.Tracing.Tests.csproj +++ b/tests/Relayer.Tracing.Tests/Relayer.Tracing.Tests.csproj @@ -6,5 +6,7 @@ + diff --git a/website/docs/guides/handlers.md b/website/docs/guides/handlers.md index 9896c8cd1..44de2ef1e 100644 --- a/website/docs/guides/handlers.md +++ b/website/docs/guides/handlers.md @@ -23,7 +23,7 @@ public sealed class OrderPlacedHandler(AppDbContext db, ISender sender) : IHandl ## Batch handlers -A batch handler receives several messages at once. Each message can succeed or fail independently, and only the failed ones enter the failure pipeline: +A batch handler receives several messages at once. Each message can succeed or fail independently. Without buffered direct sends, only failed items enter the failure pipeline: ```csharp public sealed class AuditHandler(AuditStore store) : IBatchHandler @@ -40,13 +40,16 @@ Return `BatchResult.Success` when every message succeeded. Configure the existing consumer declaration with `.Batch(maxSize, maxWait)`. The core composes generated batch dispatch in one fresh scope per batch attempt. -Only failed items are retried; an exception from the handler fails every item in +Normally only failed items are retried; an exception from the handler fails every item in that invocation. Success waits for asynchronous scope disposal and durable work before the adapter receives settlement decisions. Direct sends from the scoped `ISender` are buffered until the entire attempt -succeeds. A partial failure with buffered sends fails the receive call because -those sends cannot be attributed to individual items. Use explicit per-message +succeeds. A partial failure with buffered sends discards those sends and fails +every item in the attempt because sends cannot be attributed to individual items. +The normal retry, redelivery and dead-letter policy handles every item, including +otherwise successful items, so poison messages cannot stall the batch indefinitely. +Use explicit per-message durable outbox transactions when partial success also produces messages. Do not retain the borrowed batch or its item contexts after handler completion. diff --git a/website/docs/transports/consume-pipeline.md b/website/docs/transports/consume-pipeline.md index 7a2ec475c..f66c0cbbc 100644 --- a/website/docs/transports/consume-pipeline.md +++ b/website/docs/transports/consume-pipeline.md @@ -144,8 +144,10 @@ delegate remains available to transport integrations that own durable failure ha Successful results wait for asynchronous scope disposal and buffered sends. Failed attempts discard their buffered direct sends. A partially failed attempt with buffered -sends fails the entire receive call: one scoped sender cannot attribute those sends -to individual messages. Use explicit per-message durable outbox transactions when +sends discards those sends and routes every item through the normal retry, +redelivery and dead-letter policy: one scoped sender cannot attribute those sends +to individual messages. Otherwise successful items can retry or dead-letter too; +no item settles successfully with its outgoing messages discarded. Use explicit per-message durable outbox transactions when partial success also produces messages (D28). Failure handling and disposal errors propagate without publishing any batch dispositions. From e278c57e4d6687e7184c613244c77326d843642c Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:43:41 +0000 Subject: [PATCH 3/5] fix: honor batch delivery cancellation (#11) --- src/Relayer/Pipeline/BatchExecution.cs | 12 +++- tests/Relayer.Tests/BatchPipelineTests.cs | 76 +++++++++++++++++++++ website/docs/transports/consume-pipeline.md | 9 ++- 3 files changed, 93 insertions(+), 4 deletions(-) diff --git a/src/Relayer/Pipeline/BatchExecution.cs b/src/Relayer/Pipeline/BatchExecution.cs index d605d1aee..36bb838cb 100644 --- a/src/Relayer/Pipeline/BatchExecution.cs +++ b/src/Relayer/Pipeline/BatchExecution.cs @@ -83,7 +83,11 @@ internal async ValueTask ProcessAsync(ConsumePipeline owner, ReadOnlyMemory(); if (service is not null && service is not Sender) throw new InvalidOperationException("Batch execution requires Relayer's scoped ISender to buffer failed-attempt sends."); @@ -98,7 +102,11 @@ internal async ValueTask ProcessAsync(ConsumePipeline owner, ReadOnlyMemory d.Kind == DispositionKind.Complete)).IsTrue(); } + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Delivery_cancellation_during_handler_or_disposal_discards_sends_and_releases_contexts(bool duringDisposal) + { + await using var provider = Provider(); + var control = provider.GetRequiredService(); + var transport = provider.GetRequiredService(); + using var cancellation = new CancellationTokenSource(); + var disposalDone = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + if (duringDisposal) + { + control.Disposal = disposalDone.Task; + control.DisposalStarted = new(TaskCreationOptions.RunContinuationsAsynchronously); + } + control.Invoke = async (batch, _) => + { + await batch.Items[0].Context.Services.GetRequiredService().SendNowAsync(new Payload()); + if (!duringDisposal) cancellation.Cancel(); + return BatchResult.Success; + }; + var failures = 0; + var pipeline = Consumer(provider, (_, _, _) => { failures++; return default; }); + var message = new ConsumeMessage { MessageId = "cancelled", MessageType = new("batch.payload", 1), Body = new(new byte[] { 1 }) }; + { + using var first = pipeline.RentContext(message); + using var second = pipeline.RentContext(message, cancellation.Token); + var contexts = new[] { first, second }; + var pending = pipeline.ProcessBatchAsync(contexts); + if (duringDisposal) + { + await control.DisposalStarted!.Task; + cancellation.Cancel(); + disposalDone.SetResult(); + } + await Assert.That(async () => await pending).Throws(); + await Assert.That(transport.Sends).IsEqualTo(0); + await Assert.That(failures).IsEqualTo(0); + await Assert.That(control.Disposed).IsEqualTo(1); + } + control.Invoke = null; + using var reused = pipeline.RentContext(message); + await pipeline.ProcessBatchAsync(new[] { reused }); + await Assert.That(transport.Sends).IsEqualTo(0); + } + + [Test] + public async Task Delivery_cancelled_between_attempts_is_not_dispatched_again() + { + await using var provider = Provider(); + using var cancellation = new CancellationTokenSource(); + var control = provider.GetRequiredService(); + control.Invoke = (_, _) => new(BatchResult.PartialFailure(new Dictionary { [1] = new Exception("retry") })); + var failures = new FailurePipeline(provider, "test", "source", "batch", new() { RetryDelays = new[] { TimeSpan.Zero }, Jitter = 0 }); + var pipeline = new ConsumePipelineBuilder(provider.GetRequiredService(), + provider.GetRequiredService(), provider.GetRequiredService(), + failures, new CancelOnClassify(cancellation)) + .BuildBatch(provider.GetRequiredService().GetBatchHandler(), Definition(provider)); + var message = new ConsumeMessage { MessageId = "retry", MessageType = new("batch.payload", 1), Body = new(new byte[] { 1 }) }; + using var first = pipeline.RentContext(message); + using var second = pipeline.RentContext(message, cancellation.Token); + await Assert.That(async () => await pipeline.ProcessBatchAsync(new[] { first, second })).Throws(); + await Assert.That(control.Scopes.Count).IsEqualTo(1); + await Assert.That(control.Disposed).IsEqualTo(1); + await Assert.That(provider.GetRequiredService().Sends).IsEqualTo(0); + } + [Test] public async Task Each_batch_owns_one_scope_and_concurrent_batches_do_not_share_storage() { @@ -461,6 +528,15 @@ public sealed class Control public Task? Disposal { get; set; } public TaskCompletionSource? DisposalStarted { get; set; } } + private sealed class CancelOnClassify(CancellationTokenSource cancellation) : IFailureClassifier + { + public FailureAction Classify(Exception exception, MessageContext context) + { + cancellation.Cancel(); + return FailureAction.Retry; + } + } + public sealed class Lifetime(Control control) : IAsyncDisposable { public async ValueTask DisposeAsync() diff --git a/website/docs/transports/consume-pipeline.md b/website/docs/transports/consume-pipeline.md index f66c0cbbc..9dc94f79c 100644 --- a/website/docs/transports/consume-pipeline.md +++ b/website/docs/transports/consume-pipeline.md @@ -142,8 +142,13 @@ The executable `FailurePipeline` retries only failed items, in a fresh scope, th produces durable per-message redelivery or dead-letter decisions. The explicit failure delegate remains available to transport integrations that own durable failure handling. -Successful results wait for asynchronous scope disposal and buffered sends. Failed -attempts discard their buffered direct sends. A partially failed attempt with buffered +Successful results wait for asynchronous scope disposal and buffered sends. +The batch-call token and each active delivery token are checked before handler +invocation and again after scope disposal, before flushing sends or handling failures. +Delivery cancellation also prevents that item from entering another retry invocation, +even when `ProcessBatchAsync` uses its default batch-call token. Cancellation propagates +without publishing batch dispositions; buffered sends from the cancelled attempt are discarded. +Failed attempts discard their buffered direct sends. A partially failed attempt with buffered sends discards those sends and routes every item through the normal retry, redelivery and dead-letter policy: one scoped sender cannot attribute those sends to individual messages. Otherwise successful items can retry or dead-letter too; From ac12c3432a435f80ff03e0703ecd8b820d9ea4b1 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:52:33 +0000 Subject: [PATCH 4/5] fix: avoid decoding batch traceparent strings (#11) --- .../BatchConsumePipelineBenchmarks.cs | 27 +++++++++++++------ src/Relayer/Pipeline/BatchExecution.cs | 16 ++++++----- tests/Relayer.AotSmoke/Program.cs | 25 +++++++++++++++-- tests/Relayer.Tests/BatchPipelineTests.cs | 16 ++++++++--- .../BatchTracingTests.cs | 20 ++++++++------ website/docs/transports/consume-pipeline.md | 4 ++- 6 files changed, 78 insertions(+), 30 deletions(-) diff --git a/benchmarks/Relayer.Benchmarks/BatchConsumePipelineBenchmarks.cs b/benchmarks/Relayer.Benchmarks/BatchConsumePipelineBenchmarks.cs index 204628d64..e1ff896bd 100644 --- a/benchmarks/Relayer.Benchmarks/BatchConsumePipelineBenchmarks.cs +++ b/benchmarks/Relayer.Benchmarks/BatchConsumePipelineBenchmarks.cs @@ -1,5 +1,6 @@ using System.Buffers; using System.Diagnostics; +using System.Text; using BenchmarkDotNet.Attributes; using Microsoft.Extensions.DependencyInjection; using Relayer.Serialization; @@ -25,12 +26,13 @@ public class BatchConsumePipelineBenchmarks private Activity _ambient = null!; private ActivityLink[] _links = null!; private KeyValuePair[] _tags = null!; + private readonly HeaderNames _headerNames = new(); [Params(1, 10, 100)] public int BatchSize { get; set; } - [Params(false, true)] - public bool DropTracing { get; set; } + [Params(TracingMode.None, TracingMode.Text, TracingMode.Utf8)] + public TracingMode Tracing { get; set; } [GlobalSetup] public void Setup() @@ -51,7 +53,7 @@ public void Setup() _source = new ActivitySource("Relayer"); _listener = new ActivityListener { - ShouldListenTo = source => DropTracing && ReferenceEquals(source, _source), + ShouldListenTo = source => Tracing != TracingMode.None && ReferenceEquals(source, _source), Sample = static (ref ActivityCreationOptions _) => ActivitySamplingResult.None }; ActivitySource.AddActivityListener(_listener); @@ -65,7 +67,7 @@ public void Setup() _pipeline = new ConsumePipelineBuilder(_scopes, _provider.GetRequiredService(), _serializer, static (_, error, _) => ValueTask.FromException(error)).BuildBatch(_descriptor, definition, _source); _message = new() { MessageId = "benchmark", MessageType = new("benchmark.batch", 1), Body = ReadOnlySequence.Empty, - Headers = DropTracing ? new TraceHeaders() : null }; + Headers = Tracing != TracingMode.None ? new TraceHeaders(Tracing == TracingMode.Utf8) : null }; _contexts = new DefaultMessageContext[BatchSize]; var items = new BatchItem[BatchSize]; for (var i = 0; i < items.Length; i++) items[i] = new(_serializer.Deserialize(_message.Body), _directContext); @@ -89,10 +91,10 @@ public async ValueTask DirectScopedBatch() private Activity? StartDirectActivity() { - if (!DropTracing) return null; + if (Tracing == TracingMode.None) return null; for (var i = 0; i < BatchSize; i++) { - ActivityContext.TryParse(TraceHeaders.Parent, null, true, out var context); + var context = MessageCreationContext.Read(_message.Headers!, _headerNames); _links[i] = new(context); } return _source.StartActivity("process source", ActivityKind.Consumer, Activity.Current?.Context ?? default, _tags, _links); @@ -138,12 +140,21 @@ private sealed class Serializer : IMessageSerializer public TMessage Deserialize(ReadOnlySequence source) => (TMessage)(object)_payload; public void Serialize(TMessage message, IBufferWriter destination) => throw new NotSupportedException(); } - private sealed class TraceHeaders : MessageHeaders + public enum TracingMode { None, Text, Utf8 } + + private readonly struct CreationHeaderReader : IMessageHeaderReader + { + public static bool TryGetHeader(MessageHeaders message, string name, out WireString value) => + message.TryGetValue(name, out value); + } + + private sealed class TraceHeaders(bool utf8) : MessageHeaders { internal const string Parent = "00-11111111111111111111111111111111-2222222222222222-01"; + private readonly WireString _parent = utf8 ? new(Encoding.UTF8.GetBytes(Parent)) : new(Parent); public override bool TryGetValue(string name, out WireString value) { - value = name == "traceparent" ? new(Parent) : default; + value = name == "traceparent" ? _parent : default; return !value.IsEmpty; } } diff --git a/src/Relayer/Pipeline/BatchExecution.cs b/src/Relayer/Pipeline/BatchExecution.cs index 36bb838cb..075b7e77c 100644 --- a/src/Relayer/Pipeline/BatchExecution.cs +++ b/src/Relayer/Pipeline/BatchExecution.cs @@ -15,6 +15,7 @@ internal sealed class BatchExecution private readonly ActivitySource? _source; private readonly string _spanName; private readonly string _destination; + private readonly HeaderNames _headerNames = new(); private readonly KeyValuePair[] _batchCountTags; private readonly State?[] _states; internal int Size { get; } @@ -186,13 +187,8 @@ private static void RecordError(Activity? activity, Exception error) if (_source is null || !_source.HasListeners()) return null; for (var i = 0; i < contexts.Length; i++) { - var headers = contexts.Span[i].Headers; - if (headers.TryGetValue("traceparent", out var parent)) - { - var traceState = headers.TryGetValue("tracestate", out var value) ? value.ToString() : null; - if (ActivityContext.TryParse(parent.ToString(), traceState, true, out var creation)) - state.Links.Add(new(creation)); - } + var creation = MessageCreationContext.Read(contexts.Span[i].Headers, _headerNames); + if (creation != default) state.Links.Add(new(creation)); } state.Tags[^1] = _batchCountTags[contexts.Length - 1]; // ActivitySource consumes these reusable sampling inputs synchronously. @@ -207,6 +203,12 @@ private State Rent() return new State(Size, _destination); } + private readonly struct CreationHeaderReader : IMessageHeaderReader + { + public static bool TryGetHeader(MessageHeaders message, string name, out WireString value) => + message.TryGetValue(name, out value); + } + private sealed class State(int size, string destination) { internal readonly DefaultMessageContext[] Active = new DefaultMessageContext[size]; diff --git a/tests/Relayer.AotSmoke/Program.cs b/tests/Relayer.AotSmoke/Program.cs index ad4cd3361..4e4ee2b2f 100644 --- a/tests/Relayer.AotSmoke/Program.cs +++ b/tests/Relayer.AotSmoke/Program.cs @@ -140,12 +140,21 @@ throw new InvalidOperationException("Failure handling stalled the consumer or rediscovered capabilities."); Console.WriteLine("Executable failure handling and generated error metadata passed under Native AOT."); var batchDefinition = provider.GetRequiredService().Transports[0].Consumers[1]; +Activity? batchActivity = null; +using var batchListener = new ActivityListener +{ + ShouldListenTo = source => ReferenceEquals(source, tracing.Source), + Sample = static (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded, + ActivityStopped = activity => batchActivity = activity, +}; +ActivitySource.AddActivityListener(batchListener); var batchConsumer = new ConsumePipelineBuilder(provider.GetRequiredService(), provider.GetRequiredService(), serializer, static (_, error, _) => ValueTask.FromException(error)) - .BuildBatch(handlers.GetBatchHandler(), batchDefinition); + .BuildBatch(handlers.GetBatchHandler(), batchDefinition, tracing.Source); var countBuffer = new ArrayBufferWriter(); serializer.Serialize(new Count(7), countBuffer); -var countMessage = new ConsumeMessage { MessageId = "batch-count", MessageType = new("smoke.count", 1), Body = new(countBuffer.WrittenMemory) }; +var countMessage = new ConsumeMessage { MessageId = "batch-count", MessageType = new("smoke.count", 1), Body = new(countBuffer.WrittenMemory), + Headers = new SmokeBatchHeaders() }; var batchReceiver = new BatchReceiveExecutor(provider, "smoke", batchDefinition, "aot-batch", singleReceive: (destination, _, _) => { destination.Span[0] = countMessage; return new(1); }); var receivedBatch = new ConsumeMessage[2]; @@ -154,6 +163,9 @@ using (var firstCount = batchConsumer.RentContext(receivedBatch[0])) using (var secondCount = batchConsumer.RentContext(receivedBatch[1])) await batchConsumer.ProcessBatchAsync(new[] { firstCount, secondCount }); +if (batchActivity is null || batchActivity.Links.Count() != 2 || + batchActivity.Links.Any(link => !link.Context.IsRemote || link.Context.TraceId.ToString() != "0123456789abcdef0123456789abcdef")) + throw new InvalidOperationException("UTF-8 batch creation links failed under Native AOT."); Console.WriteLine("Generated batch composition and client-side executor passed under Native AOT."); var sender = scope.ServiceProvider.GetRequiredService(); await sender.SendAsync(message, options => options.ConfigureNative(static native => native.Value = 7)); @@ -217,6 +229,15 @@ public ValueTask HandleAsync(Order message, MessageContext context, Cancellation { public static bool TryGetHeader(Dictionary message, string name, out WireString value) => message.TryGetValue(name, out value); } +internal sealed class SmokeBatchHeaders : MessageHeaders +{ + private readonly WireString _parent = new("00-0123456789abcdef0123456789abcdef-0123456789abcdef-01"u8.ToArray()); + public override bool TryGetValue(string name, out WireString value) + { + value = name == "traceparent" ? _parent : default; + return !value.IsEmpty; + } +} internal readonly struct SmokeBinding : IMessageBinding { public static ReadOnlySequence GetBody(SmokeIncoming message) => message.Body; diff --git a/tests/Relayer.Tests/BatchPipelineTests.cs b/tests/Relayer.Tests/BatchPipelineTests.cs index 78f5258b7..737cb452d 100644 --- a/tests/Relayer.Tests/BatchPipelineTests.cs +++ b/tests/Relayer.Tests/BatchPipelineTests.cs @@ -261,9 +261,11 @@ public async Task Each_batch_owns_one_scope_and_concurrent_batches_do_not_share_ } [Test] - [Arguments(false)] - [Arguments(true)] - public async Task Batch_span_links_every_creation_context_and_uses_only_ambient_parent(bool ambient) + [Arguments(false, false)] + [Arguments(false, true)] + [Arguments(true, false)] + [Arguments(true, true)] + public async Task Batch_span_links_every_creation_context_and_uses_only_ambient_parent(bool ambient, bool utf8) { await using var provider = Provider(); using var source = new ActivitySource("Relayer"); @@ -285,6 +287,9 @@ public async Task Batch_span_links_every_creation_context_and_uses_only_ambient_ var expectedActivity = Activity.Current; var expectedParent = expectedActivity?.Context ?? default; var input = Input(3); + if (utf8) + for (var i = 0; i < input.Length; i++) + input[i] = input[i] with { TraceParent = new("00-11111111111111111111111111111111-2222222222222222-01"u8.ToArray()) }; var pipeline = Pipeline(provider, source: source); await pipeline.ProcessBatchAsync(input, new Disposition[3]); await Assert.That(observed!.DisplayName).IsEqualTo("process source"); @@ -294,6 +299,8 @@ public async Task Batch_span_links_every_creation_context_and_uses_only_ambient_ await Assert.That(observed.GetTagItem("messaging.operation.type") as string).IsEqualTo("process"); await Assert.That(observed.Links.Count()).IsEqualTo(3); await Assert.That(observed.Links.All(link => link.Context.IsRemote)).IsTrue(); + await Assert.That(observed.Links.All(link => link.Context.TraceId.ToString() == "11111111111111111111111111111111" && + link.Context.SpanId.ToString() == "2222222222222222" && link.Context.TraceFlags == ActivityTraceFlags.Recorded)).IsTrue(); await Assert.That(sampledCount).IsEqualTo(3); await Assert.That(Activity.Current).IsSameReferenceAs(expectedActivity); await pipeline.ProcessBatchAsync(input.AsMemory(0, 1), new Disposition[1]); @@ -570,6 +577,7 @@ internal sealed class Serializer : IMessageSerializer } internal sealed record Incoming(string Id) { + public WireString TraceParent { get; init; } = new("00-11111111111111111111111111111111-2222222222222222-01"); public string Type { get; init; } = "batch.payload;v=1"; public byte Value { get; init; } = 1; } @@ -579,7 +587,7 @@ internal sealed record Incoming(string Id) public static int? GetDeliveryCount(Incoming message) => 1; public static bool TryGetHeader(Incoming message, string name, out WireString value) { - value = name switch { "ce_id" => new(message.Id), "ce_type" => new(message.Type), "traceparent" => new("00-11111111111111111111111111111111-2222222222222222-01"), _ => default }; + value = name switch { "ce_id" => new(message.Id), "ce_type" => new(message.Type), "traceparent" => message.TraceParent, _ => default }; return !value.IsEmpty; } } diff --git a/tests/Relayer.Tracing.Tests/BatchTracingTests.cs b/tests/Relayer.Tracing.Tests/BatchTracingTests.cs index f1b23f39f..4106a8939 100644 --- a/tests/Relayer.Tracing.Tests/BatchTracingTests.cs +++ b/tests/Relayer.Tracing.Tests/BatchTracingTests.cs @@ -1,5 +1,6 @@ using System.Buffers; using System.Diagnostics; +using System.Text; using Microsoft.Extensions.DependencyInjection; using Relayer.Serialization; @@ -8,11 +9,13 @@ namespace Relayer.Tests; public class BatchTracingTests { [Test] - [Arguments(1, false)] - [Arguments(1, true)] - [Arguments(10, false)] - [Arguments(10, true)] - public async Task Dropped_batch_spans_add_no_allocations_beyond_scope_and_framework_context_parsing(int size, bool links) + [Arguments(1, false, false)] + [Arguments(1, true, false)] + [Arguments(1, true, true)] + [Arguments(10, false, false)] + [Arguments(10, true, false)] + [Arguments(10, true, true)] + public async Task Dropped_batch_spans_add_no_allocations_beyond_scope_and_framework_context_parsing(int size, bool links, bool utf8) { var services = new ServiceCollection(); services.AddSingleton(); @@ -41,7 +44,7 @@ public async Task Dropped_batch_spans_add_no_allocations_beyond_scope_and_framew var message = new ConsumeMessage { MessageId = "allocation", MessageType = new("batch.tracing", 1), Body = ReadOnlySequence.Empty, - Headers = links ? new TraceHeaders() : null + Headers = links ? new TraceHeaders(utf8) : null }; var contexts = new DefaultMessageContext[size]; for (var iteration = 0; iteration < 1000; iteration++) @@ -87,12 +90,13 @@ private sealed class Serializer : IMessageSerializer public TMessage Deserialize(ReadOnlySequence source) => (TMessage)(object)_payload; public void Serialize(TMessage message, IBufferWriter destination) => throw new NotSupportedException(); } - private sealed class TraceHeaders : MessageHeaders + private sealed class TraceHeaders(bool utf8) : MessageHeaders { internal const string Parent = "00-11111111111111111111111111111111-2222222222222222-01"; + private readonly WireString _parent = utf8 ? new(Encoding.UTF8.GetBytes(Parent)) : new(Parent); public override bool TryGetValue(string name, out WireString value) { - value = name == "traceparent" ? new(Parent) : default; + value = name == "traceparent" ? _parent : default; return !value.IsEmpty; } } diff --git a/website/docs/transports/consume-pipeline.md b/website/docs/transports/consume-pipeline.md index 9dc94f79c..95a623de9 100644 --- a/website/docs/transports/consume-pipeline.md +++ b/website/docs/transports/consume-pipeline.md @@ -160,7 +160,9 @@ Pass the application's shared `Relayer` ActivitySource to `BuildBatch` to trace `process {source}` CONSUMER span for the batch, including retries. It links each valid creation context and uses only the ambient span as parent. It includes `messaging.batch.message_count`. The caller owns the source; no process-wide source -or second source owner is created. This is the batch execution seam for #13's shared +or second source owner is created. UTF-8 traceparent headers are parsed without allocating +an intermediate header string; UTF-8 tracestate decoding can still allocate. +This is the batch execution seam for #13's shared tracing integration. Native settlement and its tracing remain the adapter's work. Do not retain the borrowed `Batch.Items`, message contexts, or native features after handler completion. Pools retain bounded reusable storage sized by the declaration's From da14c8302fe3108b761f76f274c8d0422bcc6d85 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:05:50 +0000 Subject: [PATCH 5/5] fix: cancel buffered batch sends with deliveries (#11) --- .../BatchBufferedSendBenchmarks.cs | 107 ++++++++++++++++++ src/Relayer/Pipeline/BatchExecution.cs | 37 +++++- tests/Relayer.Tests/BatchPipelineTests.cs | 82 +++++++++++++- website/docs/guides/handlers.md | 5 + 4 files changed, 224 insertions(+), 7 deletions(-) create mode 100644 benchmarks/Relayer.Benchmarks/BatchBufferedSendBenchmarks.cs diff --git a/benchmarks/Relayer.Benchmarks/BatchBufferedSendBenchmarks.cs b/benchmarks/Relayer.Benchmarks/BatchBufferedSendBenchmarks.cs new file mode 100644 index 000000000..2e90dec5d --- /dev/null +++ b/benchmarks/Relayer.Benchmarks/BatchBufferedSendBenchmarks.cs @@ -0,0 +1,107 @@ +using System.Buffers; +using BenchmarkDotNet.Attributes; +using Microsoft.Extensions.DependencyInjection; +using Relayer.Serialization; +using Relayer.Transports; + +namespace Relayer.Benchmarks; + +/// Buffered batch sends with shared or distinct cancellable delivery tokens. Results are per batch. +[MemoryDiagnoser] +public class BatchBufferedSendBenchmarks +{ + private ServiceProvider _provider = null!; + private ConsumePipeline _pipeline = null!; + private DefaultMessageContext[] _contexts = null!; + private CancellationTokenSource[] _deliveries = null!; + private readonly CancellationTokenSource _batch = new(); + private readonly ConsumeMessage _message = new() + { + MessageId = "benchmark", MessageType = new("benchmark.buffered-batch", 1), Body = ReadOnlySequence.Empty + }; + + [Params(1, 10, 100)] + public int BatchSize { get; set; } + + [Params(false, true)] + public bool DistinctDeliveryTokens { get; set; } + + [GlobalSetup] + public void Setup() + { + var services = new ServiceCollection(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddRelayer(builder => + { + builder.MessageTypes.Add("benchmark.buffered-batch"); + builder.AddTransport("benchmark", transport => + { + transport.Send("destination"); + transport.Consume("source", consumer => consumer.Handler().Batch(BatchSize, TimeSpan.FromSeconds(1))); + }); + }); + _provider = services.BuildServiceProvider(); + _pipeline = new ConsumePipelineBuilder(_provider.GetRequiredService(), + _provider.GetRequiredService(), _provider.GetRequiredService(), + static (_, error, _) => ValueTask.FromException(error)) + .BuildBatch(_provider.GetRequiredService().GetBatchHandler(), + _provider.GetRequiredService().Transports[0].Consumers[0]); + _contexts = new DefaultMessageContext[BatchSize]; + _deliveries = new CancellationTokenSource[DistinctDeliveryTokens ? BatchSize : 1]; + for (var i = 0; i < _deliveries.Length; i++) _deliveries[i] = new(); + } + + [Benchmark] + public async ValueTask BufferedBatch() + { + for (var i = 0; i < BatchSize; i++) + _contexts[i] = _pipeline.RentContext(_message, _deliveries[DistinctDeliveryTokens ? i : 0].Token); + try { await _pipeline.ProcessBatchAsync(_contexts, _batch.Token).ConfigureAwait(false); } + finally + { + for (var i = 0; i < BatchSize; i++) { _contexts[i].Dispose(); _contexts[i] = null!; } + } + } + + [GlobalCleanup] + public async ValueTask Cleanup() + { + foreach (var delivery in _deliveries) delivery.Dispose(); + _batch.Dispose(); + await _provider.DisposeAsync().ConfigureAwait(false); + } + + public sealed class Options; + [Message("benchmark.buffered-batch")] + public sealed class Payload; + public sealed class Handler : IBatchHandler + { + public async ValueTask HandleAsync(Batch batch, CancellationToken cancellationToken) + { + var sender = batch.Items[0].Context.Services.GetRequiredService(); + for (var i = 0; i < batch.Count; i++) + await sender.SendNowAsync(batch.Items[i].Message, cancellationToken).ConfigureAwait(false); + return BatchResult.Success; + } + } + private sealed class Serializer : IMessageSerializer + { + private readonly Payload _payload = new(); + public string ContentType => "benchmark/cached"; + public TMessage Deserialize(ReadOnlySequence source) => (TMessage)(object)_payload; + public void Serialize(TMessage message, IBufferWriter destination) { destination.GetSpan(1)[0] = 1; destination.Advance(1); } + } + private sealed class Transport : ITransport + { + public string Name => "benchmark"; + public TransportCapabilities GetCapabilities(string endpoint) => new(); + public ValueTask SendAsync(OutgoingMessage message, CancellationToken cancellationToken) => default; + public ValueTask SendBatchAsync(ReadOnlyMemory messages, CancellationToken cancellationToken) => throw new NotSupportedException(); + public ValueTask ApplyTopologyAsync(TopologyMode mode, CancellationToken cancellationToken) => new(new TopologyReport([])); + public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public ValueTask DisposeAsync() => default; + } +} diff --git a/src/Relayer/Pipeline/BatchExecution.cs b/src/Relayer/Pipeline/BatchExecution.cs index 075b7e77c..21a97001c 100644 --- a/src/Relayer/Pipeline/BatchExecution.cs +++ b/src/Relayer/Pipeline/BatchExecution.cs @@ -108,7 +108,7 @@ internal async ValueTask ProcessAsync(ConsumePipeline owner, ReadOnlyMemory + token.UnsafeRegister(static state => ((CancellationTokenSource)state!).Cancel(), _flushCancellation); } } diff --git a/tests/Relayer.Tests/BatchPipelineTests.cs b/tests/Relayer.Tests/BatchPipelineTests.cs index 737cb452d..762e69fb2 100644 --- a/tests/Relayer.Tests/BatchPipelineTests.cs +++ b/tests/Relayer.Tests/BatchPipelineTests.cs @@ -216,6 +216,61 @@ public async Task Delivery_cancellation_during_handler_or_disposal_discards_send await Assert.That(transport.Sends).IsEqualTo(0); } + [Test] + [Arguments(0, false)] + [Arguments(1, false)] + [Arguments(2, false)] + [Arguments(0, true)] + [Arguments(1, true)] + [Arguments(2, true)] + public async Task Cancellation_during_flush_reaches_transport_and_prevents_batch_success(int tokenIndex, bool lastSend) + { + await using var provider = Provider(); + var control = provider.GetRequiredService(); + var transport = provider.GetRequiredService(); + using var cancellation = new CancellationTokenSource(); + using var otherDelivery = new CancellationTokenSource(); + var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var observed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + control.Invoke = async (batch, _) => + { + var sender = batch.Items[0].Context.Services.GetRequiredService(); + for (var i = 0; i < 3; i++) await sender.SendNowAsync(new Payload()); + return BatchResult.Success; + }; + transport.Send = async (_, token) => + { + if (transport.Sends != (lastSend ? 3 : 1)) return; + using var registration = token.Register(() => observed.TrySetResult()); + started.TrySetResult(); + // Deliberately return success after cancellation, as a native client may do. + await release.Task; + }; + var failures = 0; + var pipeline = Consumer(provider, (_, _, _) => { failures++; return default; }); + var message = new ConsumeMessage { MessageId = "flush", MessageType = new("batch.payload", 1), Body = new(new byte[] { 1 }) }; + { + using var first = pipeline.RentContext(message, tokenIndex == 0 ? cancellation.Token : otherDelivery.Token); + using var second = pipeline.RentContext(message, tokenIndex == 1 ? cancellation.Token : otherDelivery.Token); + var pending = pipeline.ProcessBatchAsync(new[] { first, second }, tokenIndex == 2 ? cancellation.Token : default); + await started.Task; + cancellation.Cancel(); + var reachedTransport = observed.Task.IsCompleted; + release.SetResult(); + await Assert.That(async () => await pending).Throws(); + await Assert.That(reachedTransport).IsTrue(); + await Assert.That(transport.Sends).IsEqualTo(lastSend ? 3 : 1); + await Assert.That(failures).IsEqualTo(0); + await Assert.That(control.Disposed).IsEqualTo(1); + } + // A cancelled flush must release registrations and reset pooled state for a later flush. + using var reused = pipeline.RentContext(message, otherDelivery.Token); + await pipeline.ProcessBatchAsync(new[] { reused }); + await Assert.That(transport.Sends).IsEqualTo((lastSend ? 3 : 1) + 3); + otherDelivery.Cancel(); + } + [Test] public async Task Delivery_cancelled_between_attempts_is_not_dispatched_again() { @@ -407,9 +462,14 @@ public async Task Batch_context_ownership_and_single_message_entry_are_validated } [Test] - public async Task Warmed_batches_add_no_allocations_beyond_identical_fresh_DI_scope_and_sender() + [Arguments(false)] + [Arguments(true)] + public async Task Warmed_batches_add_no_allocations_beyond_identical_fresh_DI_scope_and_sender(bool bufferedSends) { await using var provider = Provider(size: 10); + provider.GetRequiredService().BufferedSends = bufferedSends; + using var batchCancellation = new CancellationTokenSource(); + var deliveries = Enumerable.Range(0, 10).Select(_ => new CancellationTokenSource()).ToArray(); var scopes = provider.GetRequiredService(); var consumer = new ConsumePipelineBuilder(scopes, provider.GetRequiredService(), provider.GetRequiredService(), static (_, error, _) => ValueTask.FromException(error)) @@ -418,8 +478,8 @@ public async Task Warmed_batches_add_no_allocations_beyond_identical_fresh_DI_sc var contexts = new DefaultMessageContext[10]; for (var iteration = 0; iteration < 1000; iteration++) { - for (var i = 0; i < contexts.Length; i++) contexts[i] = consumer.RentContext(message); - await consumer.ProcessBatchAsync(contexts); + for (var i = 0; i < contexts.Length; i++) contexts[i] = consumer.RentContext(message, deliveries[i].Token); + await consumer.ProcessBatchAsync(contexts, batchCancellation.Token); for (var i = 0; i < contexts.Length; i++) contexts[i].Dispose(); using var scope = scopes.CreateScope(); _ = scope.ServiceProvider.GetRequiredService(); @@ -434,11 +494,12 @@ public async Task Warmed_batches_add_no_allocations_beyond_identical_fresh_DI_sc start = GC.GetAllocatedBytesForCurrentThread(); for (var iteration = 0; iteration < 1000; iteration++) { - for (var i = 0; i < contexts.Length; i++) contexts[i] = consumer.RentContext(message); - await consumer.ProcessBatchAsync(contexts); + for (var i = 0; i < contexts.Length; i++) contexts[i] = consumer.RentContext(message, deliveries[i].Token); + await consumer.ProcessBatchAsync(contexts, batchCancellation.Token); for (var i = 0; i < contexts.Length; i++) contexts[i].Dispose(); } var composed = GC.GetAllocatedBytesForCurrentThread() - start; + foreach (var delivery in deliveries) delivery.Dispose(); await Assert.That(composed).IsEqualTo(baseline); } @@ -566,7 +627,16 @@ public ValueTask HandleAsync(Batch batch, CancellationToke } public sealed class AllocationHandler : IBatchHandler { - public ValueTask HandleAsync(Batch batch, CancellationToken cancellationToken) => new(BatchResult.Success); + public bool BufferedSends { get; set; } + public async ValueTask HandleAsync(Batch batch, CancellationToken cancellationToken) + { + if (BufferedSends) + { + var sender = batch.Items[0].Context.Services.GetRequiredService(); + for (var i = 0; i < batch.Count; i++) await sender.SendNowAsync(batch.Items[i].Message, cancellationToken); + } + return BatchResult.Success; + } } internal sealed class Serializer : IMessageSerializer { diff --git a/website/docs/guides/handlers.md b/website/docs/guides/handlers.md index 44de2ef1e..1018955f2 100644 --- a/website/docs/guides/handlers.md +++ b/website/docs/guides/handlers.md @@ -53,6 +53,11 @@ Use explicit per-message durable outbox transactions when partial success also produces messages. Do not retain the borrowed batch or its item contexts after handler completion. +Cancellation of any active delivery or the batch call cancels an in-flight +buffered-send flush, including when the batch-call token is omitted. The batch +cannot complete successfully after cancellation. Sends already accepted by the +broker can repeat on redelivery; cancellation does not undo them. + Adapters must install a native or core client-side receive executor before starting consumers; declaring a size does not supply one. The core execution seam is available now; the in-memory hosted adapter still explicitly rejects