From 9e397ae9db89746270c122982424b22d77798696 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 20:28:01 +0000 Subject: [PATCH 1/2] fix: retain send tracing states above 64 concurrent sends (#131) --- .../SendTracingConcurrencyBenchmarks.cs | 108 ++++++++ src/Relayer/Telemetry/SendTracing.cs | 47 +++- .../SendTracingPoolTests.cs | 250 ++++++++++++++++++ website/docs/transports/authoring.md | 4 +- 4 files changed, 397 insertions(+), 12 deletions(-) create mode 100644 benchmarks/Relayer.Benchmarks/SendTracingConcurrencyBenchmarks.cs create mode 100644 tests/Relayer.Tracing.Tests/SendTracingPoolTests.cs diff --git a/benchmarks/Relayer.Benchmarks/SendTracingConcurrencyBenchmarks.cs b/benchmarks/Relayer.Benchmarks/SendTracingConcurrencyBenchmarks.cs new file mode 100644 index 000000000..23084498a --- /dev/null +++ b/benchmarks/Relayer.Benchmarks/SendTracingConcurrencyBenchmarks.cs @@ -0,0 +1,108 @@ +using System.Diagnostics; +using System.Threading.Tasks.Sources; +using BenchmarkDotNet.Attributes; +using Microsoft.Extensions.Options; + +namespace Relayer.Benchmarks; + +/// +/// Measures complete warmed bursts with deterministic overlapping native sends. Totals are per burst and include +/// Activity and framework async-builder costs; SendTracingPoolTests separately isolate preparation storage. +/// +[MemoryDiagnoser] +public class SendTracingConcurrencyBenchmarks +{ + private MessageTracing _tracing = null!; + private SendTracing _send = null!; + private ActivityListener _listener = null!; + private Activity _ambient = null!; + private PendingSend[] _native = null!; + private ValueTask[] _pending = null!; + private int _next; + private readonly OutgoingMessage[] _messages = [new("orders", new byte[] { 1 }), new("orders", new byte[] { 2 })]; + + [Params(1, 64, 128)] + public int Concurrency { get; set; } + + [Params(false, true)] + public bool Batch { get; set; } + + [Params("Drop", "Record")] + public string Mode { get; set; } = "Drop"; + + [GlobalSetup] + public void Setup() + { + _tracing = new(Options.Create(new TracingOptions()), []); + _listener = new() + { + ShouldListenTo = source => ReferenceEquals(source, _tracing.Source), + Sample = (ref ActivityCreationOptions _) => + Mode == "Drop" ? ActivitySamplingResult.None : ActivitySamplingResult.AllDataAndRecorded, + }; + ActivitySource.AddActivityListener(_listener); + _ambient = new Activity("request").Start(); + _native = new PendingSend[Concurrency]; + _pending = new ValueTask[Concurrency]; + for (var i = 0; i < _native.Length; i++) _native[i] = new(); + _send = new(_tracing, new() { System = "test.native", Destination = "orders" }, SendNative, SendBatchNative); + for (var i = 0; i < 4; i++) TracedBurst(); + } + + [Benchmark(Baseline = true)] + public void NativeBurst() + { + Reset(); + for (var i = 0; i < _pending.Length; i++) + _pending[i] = Batch ? SendBatchNative(_messages, default) : SendNative(_messages[0], default); + Complete(); + } + + [Benchmark] + public void TracedBurst() + { + Reset(); + for (var i = 0; i < _pending.Length; i++) + _pending[i] = Batch ? _send.SendBatchAsync(_messages) : _send.SendAsync(_messages[0]); + Complete(); + } + + private void Reset() + { + _next = 0; + foreach (var send in _native) send.Reset(); + } + + private ValueTask SendNative(OutgoingMessage message, CancellationToken cancellationToken) => _native[_next++].Wait(); + private ValueTask SendBatchNative(ReadOnlyMemory messages, CancellationToken cancellationToken) => _native[_next++].Wait(); + + private void Complete() + { + // Inline native completion makes each ValueTask terminal before consumption; GetResult never blocks. + for (var i = 0; i < _pending.Length; i++) + { + _native[i].Complete(); + _pending[i].GetAwaiter().GetResult(); + } + } + + [GlobalCleanup] + public void Cleanup() + { + _ambient.Dispose(); + _listener.Dispose(); + _tracing.Dispose(); + } + + private sealed class PendingSend : IValueTaskSource + { + private ManualResetValueTaskSourceCore _completion; + internal void Reset() => _completion.Reset(); + internal ValueTask Wait() => new(this, _completion.Version); + internal void Complete() => _completion.SetResult(true); + public void GetResult(short token) => _completion.GetResult(token); + public ValueTaskSourceStatus GetStatus(short token) => _completion.GetStatus(token); + public void OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags) => + _completion.OnCompleted(continuation, state, token, flags); + } +} diff --git a/src/Relayer/Telemetry/SendTracing.cs b/src/Relayer/Telemetry/SendTracing.cs index ecb3c85d1..2e1b00f51 100644 --- a/src/Relayer/Telemetry/SendTracing.cs +++ b/src/Relayer/Telemetry/SendTracing.cs @@ -23,7 +23,7 @@ public sealed class SendTracing private readonly Func, CancellationToken, ValueTask> _sendBatchNative; private readonly ILogger _logger; private readonly HeaderNames _names; - private readonly State?[] _states = new State?[64]; + private readonly PoolSegment _states = new(); /// Precomputes endpoint names and attributes supplied by the native adapter. public SendTracing(MessageTracing tracing, MessagingEndpoint endpoint, @@ -41,7 +41,7 @@ public SendTracing(MessageTracing tracing, MessagingEndpoint endpoint, _sendBatchNative = sendBatch; _logger = logger ?? NullLogger.Instance; _names = headerNames ?? new(); - _states[0] = new(); + _states.Items[0] = new(); } internal Activity? Start(ActivityContext creationContext, bool deferred) => @@ -172,23 +172,48 @@ private OutgoingMessage Prepare(State state, int index, OutgoingMessage message, private State Rent(int count) { - State? state = null; - for (var i = 0; i < _states.Length; i++) - if ((state = Interlocked.Exchange(ref _states[i], null)) is not null) break; - state ??= new(); - state.Ensure(count); - return state; + var segment = _states; + while (true) + { + for (var i = 0; i < segment.Items.Length; i++) + { + var state = Volatile.Read(ref segment.Items[i]); + if (state is null) + { + var added = new State(); + state = Interlocked.CompareExchange(ref segment.Items[i], added, null) ?? added; + } + if (Interlocked.CompareExchange(ref state.InUse, 1, 0) != 0) continue; + state.Ensure(count); + return state; + } + // Retain the observed concurrency high-water mark instead of dropping overflow states each burst. + var next = Volatile.Read(ref segment.Next); + if (next is null) + { + var added = new PoolSegment(); + next = Interlocked.CompareExchange(ref segment.Next, added, null) ?? added; + } + segment = next; + } } - private void Return(State state) + private static void Return(State state) { state.Clear(); - for (var i = 0; i < _states.Length; i++) - if (Interlocked.CompareExchange(ref _states[i], state, null) is null) return; + // States stay in their slots. Publish availability only after all borrowed storage is cleared. + Volatile.Write(ref state.InUse, 0); + } + + private sealed class PoolSegment + { + internal readonly State?[] Items = new State?[64]; + internal PoolSegment? Next; } private sealed class State { + internal int InUse; internal OutgoingMessage[] Messages = []; internal ActivityContext[] Contexts = []; internal ActivityLink[] Links = []; diff --git a/tests/Relayer.Tracing.Tests/SendTracingPoolTests.cs b/tests/Relayer.Tracing.Tests/SendTracingPoolTests.cs new file mode 100644 index 000000000..88b123e1e --- /dev/null +++ b/tests/Relayer.Tracing.Tests/SendTracingPoolTests.cs @@ -0,0 +1,250 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using Microsoft.Extensions.Options; + +namespace Relayer.Tests; + +public class SendTracingPoolTests +{ + [Test] + [Arguments(false, false)] + [Arguments(true, false)] + [Arguments(true, true)] + public async Task Overlapping_sends_reuse_preparation_storage_after_warmup(bool batch, bool createSpans) + { + using var tracing = new MessageTracing(Options.Create(new TracingOptions { CreateSpansForBatches = createSpans }), []); + using var listener = new ActivityListener + { + ShouldListenTo = source => ReferenceEquals(source, tracing.Source), + Sample = static (ref ActivityCreationOptions _) => ActivitySamplingResult.None, + }; + ActivitySource.AddActivityListener(listener); + // Exclude ActivitySource's root trace ID allocation. Dropped spans still prepare headers and batch links. + using var ambient = new Activity("request").Start(); + var sink = new AllocationSink(); + var send = new SendTracing(tracing, new() { System = "test.native", Destination = "orders" }, sink.Send, sink.SendBatch); + var messages = new[] { new OutgoingMessage("orders", new byte[] { 1 }), new("orders", new byte[] { 2 }) }; + var pending = new ValueTask[128]; + long allocated = 0; + for (var round = 0; round < 4; round++) + { + sink.Completion = new(); + allocated = 0; + for (var i = 0; i < pending.Length; i++) + { + var before = GC.GetAllocatedBytesForCurrentThread(); + pending[i] = batch ? send.SendBatchAsync(messages) : send.SendAsync(messages[0]); + // Measure through native entry, before async builder suspension. This isolates preparation storage + // from framework async state-machine pooling, which has its own bounded retention policy. + allocated += sink.EntryAllocated - before; + } + sink.Completion.SetResult(); + foreach (var operation in pending) await operation; + } + await Assert.That(allocated).IsEqualTo(0L); + } + + [Test] + [Arguments(false, false)] + [Arguments(true, false)] + [Arguments(true, true)] + public async Task Concurrent_providers_keep_borrowed_storage_exclusive_through_completion(bool batch, bool createSpans) + { + using var first = new ConcurrentFixture(batch, createSpans, "first"); + using var second = new ConcurrentFixture(batch, createSpans, "second"); + var fixtures = new[] { first, second }; + await Task.WhenAll(fixtures.SelectMany(fixture => Enumerable.Range(0, 128) + .Select(index => Task.Run(() => fixture.Start(index))))); + await VerifyBorrowedStorage(fixtures, batch, createSpans); + + // Return half the states concurrently, including faulted and cancelled sends. The other half stay borrowed. + await Task.WhenAll(fixtures.SelectMany(fixture => Enumerable.Range(0, 64).Select(index => Task.Run(() => + { + var slot = fixture.Slots[index]; + if (index % 3 == 0) slot.Completion.SetException(slot.Error); + else if (index % 3 == 1) + { + slot.Cancellation.Cancel(); + slot.Completion.SetCanceled(slot.Cancellation.Token); + } + else slot.Completion.SetResult(); + })))); + foreach (var fixture in fixtures) + { + for (var i = 0; i < 64; i++) + { + var slot = fixture.Slots[i]; + Exception? error = null; + try { await slot.Pending; } + catch (Exception caught) { error = caught; } + if (i % 3 == 0) await Assert.That(error).IsSameReferenceAs(slot.Error); + else if (i % 3 == 1) + await Assert.That(((OperationCanceledException)error!).CancellationToken).IsEqualTo(slot.Cancellation.Token); + else await Assert.That(error).IsNull(); + await Assert.That(slot.NativeCalls).IsEqualTo(1); + await Assert.That(slot.AcceptedBody).IsEqualTo(slot.Messages[0].Body); + slot.Reset(); + } + } + await Task.WhenAll(fixtures.SelectMany(fixture => Enumerable.Range(0, 64) + .Select(index => Task.Run(() => fixture.Start(index))))); + await VerifyBorrowedStorage(fixtures, batch, createSpans); + await Task.WhenAll(fixtures.SelectMany(fixture => fixture.Slots.Select(slot => Task.Run(() => slot.Completion.SetResult())))); + foreach (var fixture in fixtures) + foreach (var slot in fixture.Slots) await slot.Pending; + } + + private static async Task VerifyBorrowedStorage(ConcurrentFixture[] fixtures, bool batch, bool createSpans) + { + var headerArrays = new HashSet(ReferenceEqualityComparer.Instance); + var batchArrays = new HashSet(ReferenceEqualityComparer.Instance); + foreach (var fixture in fixtures) + { + foreach (var slot in fixture.Slots) + { + await Assert.That(slot.Pending.IsCompleted).IsFalse(); + await Assert.That(slot.NativeToken).IsEqualTo(slot.Cancellation.Token); + await Assert.That(slot.Activity!.Source).IsSameReferenceAs(fixture.Tracing.Source); + await Assert.That(slot.Activity.Duration).IsEqualTo(TimeSpan.Zero); + var message = batch ? slot.Batch.Span[0] : slot.Single; + await Assert.That(message.Body).IsEqualTo(slot.Messages[0].Body); + await Assert.That(Header(message, "owner").ToString()).IsEqualTo(fixture.Owner); + await Assert.That(Header(message, "traceparent").ToString()).IsEqualTo(slot.TraceParent); + MemoryMarshal.TryGetArray(message.Headers, out var headers); + await Assert.That(headerArrays.Add(headers.Array!)).IsTrue(); + if (!batch) continue; + MemoryMarshal.TryGetArray(slot.Batch, out var messages); + await Assert.That(batchArrays.Add(messages.Array!)).IsTrue(); + await Assert.That(slot.Batch.Length).IsEqualTo(2); + await Assert.That(slot.Batch.Span[1].Body).IsEqualTo(slot.Messages[1].Body); + await Assert.That(slot.Batch.Span[1].Headers).IsEqualTo(slot.Messages[1].Headers); + await Assert.That(slot.Activity.Links.Count()).IsEqualTo(createSpans ? 2 : 1); + await Assert.That(slot.Activity.Links.Last().Context.SpanId.ToString()).IsEqualTo("0123456789abcdef"); + if (createSpans) + { + ActivityContext.TryParse(slot.TraceParent, null, true, out var context); + await Assert.That(slot.Activity.Links.First().Context.SpanId).IsEqualTo(context.SpanId); + } + } + } + } + + private static WireString Header(OutgoingMessage message, string name) + { + foreach (var header in message.Headers.Span) + if (header.Key == name) return header.Value; + throw new InvalidOperationException($"Missing header {name}."); + } + + private sealed class ConcurrentFixture : IDisposable + { + private readonly ActivityListener _listener; + private readonly SendTracing _send; + private readonly bool _batch; + internal readonly MessageTracing Tracing; + internal readonly Slot[] Slots; + internal readonly string Owner; + + internal ConcurrentFixture(bool batch, bool createSpans, string owner) + { + _batch = batch; + Owner = owner; + Tracing = new(Options.Create(new TracingOptions { CreateSpansForBatches = createSpans }), []); + _listener = new() + { + ShouldListenTo = source => ReferenceEquals(source, Tracing.Source), + Sample = static (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded, + }; + ActivitySource.AddActivityListener(_listener); + Slots = Enumerable.Range(0, 128).Select(index => new Slot(index, owner)).ToArray(); + _send = new(Tracing, new() { System = "test.native", Destination = "orders" }, Send, SendBatch); + } + + internal void Start(int index) + { + var slot = Slots[index]; + slot.Pending = _batch ? _send.SendBatchAsync(slot.Messages, slot.Cancellation.Token) + : _send.SendAsync(slot.Messages[0], slot.Cancellation.Token); + } + + private ValueTask Send(OutgoingMessage message, CancellationToken token) + { + var slot = Slots[message.Body.Span[0]]; + slot.Single = message; + return Capture(slot, message, token); + } + + private ValueTask SendBatch(ReadOnlyMemory messages, CancellationToken token) + { + var slot = Slots[messages.Span[0].Body.Span[0]]; + slot.Batch = messages; + return Capture(slot, messages.Span[0], token); + } + + private static ValueTask Capture(Slot slot, OutgoingMessage message, CancellationToken token) + { + slot.Activity = Activity.Current; + slot.TraceParent = Header(message, "traceparent").ToString(); + slot.NativeToken = token; + // The native sink accepts the first message before a possible later batch failure. + slot.AcceptedBody = message.Body; + slot.NativeCalls++; + return new(slot.Completion.Task); + } + + public void Dispose() + { + foreach (var slot in Slots) slot.Cancellation.Dispose(); + _listener.Dispose(); + Tracing.Dispose(); + } + } + + private sealed class Slot + { + internal readonly OutgoingMessage[] Messages; + internal readonly Exception Error = new InvalidOperationException("native partial failure"); + internal CancellationTokenSource Cancellation = new(); + internal TaskCompletionSource Completion = new(); + internal ValueTask Pending; + internal OutgoingMessage Single; + internal ReadOnlyMemory Batch; + internal Activity? Activity; + internal string TraceParent = ""; + internal CancellationToken NativeToken; + internal ReadOnlyMemory AcceptedBody; + internal int NativeCalls; + + internal Slot(int index, string owner) + { + KeyValuePair[] headers = [new("owner", new(owner))]; + KeyValuePair[] external = + [new("traceparent", new("00-0123456789abcdef0123456789abcdef-0123456789abcdef-01"u8.ToArray()))]; + Messages = [new("orders", new byte[] { (byte)index, 0 }, headers), new("orders", new byte[] { (byte)index, 1 }, external)]; + } + + internal void Reset() + { + Cancellation.Dispose(); + Cancellation = new(); + Completion = new(); + NativeCalls = 0; + } + } + + private sealed class AllocationSink + { + internal TaskCompletionSource Completion = null!; + internal long EntryAllocated; + internal ValueTask Send(OutgoingMessage message, CancellationToken cancellationToken) + { + EntryAllocated = GC.GetAllocatedBytesForCurrentThread(); + return new(Completion.Task); + } + internal ValueTask SendBatch(ReadOnlyMemory messages, CancellationToken cancellationToken) + { + EntryAllocated = GC.GetAllocatedBytesForCurrentThread(); + return new(Completion.Task); + } + } +} diff --git a/website/docs/transports/authoring.md b/website/docs/transports/authoring.md index 6f73b222b..2028ca113 100644 --- a/website/docs/transports/authoring.md +++ b/website/docs/transports/authoring.md @@ -74,6 +74,8 @@ var sendTracing = new SendTracing( The seam borrows prepared headers and batch memory until the native delegate completes. It preserves body, ordering, scheduling, native callbacks, input order and partial-failure behavior. Supply the native system identifier and destination format from the semantic conventions, rather than the arbitrary registration name. Endpoint metadata and span names are computed at startup. Deferred handler sends use a create span before their envelope is copied into the attempt buffer, then a linked send span when the buffer flushes. -`InMemoryTransport` implements this seam. DI registration supplies `MessageTracing` automatically. For a standalone instance, pass `tracing:` to its constructor. Its homogeneous batches use one batch span; mixed-destination batches retain native input order and use one single-message span per message. Broker adapters remain planned; they must provide this integration when implemented. +Each endpoint retains send preparation storage up to its observed concurrency high-water mark, including workloads above 64 overlapping single or batch sends. Storage stays exclusive to a send until its native delegate completes, including failure or cancellation. Initial concurrency growth and larger batches can allocate; repeated bursts at the warmed concurrency and batch size reuse that storage without per-message locks. `System.Diagnostics` activity allocations and framework async-builder costs remain separate. Run `SendTracingConcurrencyBenchmarks` for complete burst costs with dropped and recorded spans. + +`InMemoryTransport` implements this seam. DI registration supplies `MessageTracing` automatically. For a standalone instance, pass `tracing:` to its constructor. Its homogeneous batches use one batch span; mixed-destination batches retain native input order and use one single-message span per message. The Kafka producer adapter also implements this seam. Other broker adapters must provide this integration when implemented. Run the reusable [transport conformance suite](conformance.md) against the real broker or emulator before shipping an adapter. From e97216c3ed081c41acaf9638e055a6fc69203748 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 21:16:40 +0000 Subject: [PATCH 2/2] fix: skip atomic reservations for busy tracing slots (#131) --- src/Relayer/Telemetry/SendTracing.cs | 1 + website/docs/transports/authoring.md | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Relayer/Telemetry/SendTracing.cs b/src/Relayer/Telemetry/SendTracing.cs index 2e1b00f51..ef1ecf27e 100644 --- a/src/Relayer/Telemetry/SendTracing.cs +++ b/src/Relayer/Telemetry/SendTracing.cs @@ -183,6 +183,7 @@ private State Rent(int count) var added = new State(); state = Interlocked.CompareExchange(ref segment.Items[i], added, null) ?? added; } + if (Volatile.Read(ref state.InUse) != 0) continue; if (Interlocked.CompareExchange(ref state.InUse, 1, 0) != 0) continue; state.Ensure(count); return state; diff --git a/website/docs/transports/authoring.md b/website/docs/transports/authoring.md index 2028ca113..2f7bc1689 100644 --- a/website/docs/transports/authoring.md +++ b/website/docs/transports/authoring.md @@ -74,7 +74,7 @@ var sendTracing = new SendTracing( The seam borrows prepared headers and batch memory until the native delegate completes. It preserves body, ordering, scheduling, native callbacks, input order and partial-failure behavior. Supply the native system identifier and destination format from the semantic conventions, rather than the arbitrary registration name. Endpoint metadata and span names are computed at startup. Deferred handler sends use a create span before their envelope is copied into the attempt buffer, then a linked send span when the buffer flushes. -Each endpoint retains send preparation storage up to its observed concurrency high-water mark, including workloads above 64 overlapping single or batch sends. Storage stays exclusive to a send until its native delegate completes, including failure or cancellation. Initial concurrency growth and larger batches can allocate; repeated bursts at the warmed concurrency and batch size reuse that storage without per-message locks. `System.Diagnostics` activity allocations and framework async-builder costs remain separate. Run `SendTracingConcurrencyBenchmarks` for complete burst costs with dropped and recorded spans. +Each endpoint retains send preparation storage up to its observed concurrency high-water mark, including workloads above 64 overlapping single or batch sends. Storage stays exclusive to a send until its native delegate completes, including failure or cancellation. Initial concurrency growth and larger batches can allocate; repeated bursts at the warmed concurrency and batch size reuse that storage without per-message locks. Each slot retains its largest preparation arrays and header buffers for the endpoint lifetime, so a temporary concurrency or batch-size spike can increase retained memory. `System.Diagnostics` activity allocations and framework async-builder costs remain separate. Run `SendTracingConcurrencyBenchmarks` for complete burst costs with dropped and recorded spans. `InMemoryTransport` implements this seam. DI registration supplies `MessageTracing` automatically. For a standalone instance, pass `tracing:` to its constructor. Its homogeneous batches use one batch span; mixed-destination batches retain native input order and use one single-message span per message. The Kafka producer adapter also implements this seam. Other broker adapters must provide this integration when implemented.