From 261dd0045c0c301446db9d124aeb20a63da2b5b4 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:46:38 +0000 Subject: [PATCH 1/8] feat: add consume metrics and failure logging (#84) --- .../Relayer.Benchmarks/TelemetryBenchmarks.cs | 95 +++++ docs/design.md | 2 + docs/telemetry.md | 40 ++ .../RelayerServiceCollectionExtensions.cs | 1 + src/Relayer/Pipeline/ConsumePipeline.cs | 56 ++- .../Pipeline/ConsumePipelineBuilder.cs | 29 +- src/Relayer/Pipeline/DefaultMessageContext.cs | 16 + src/Relayer/Pipeline/ReceiveMessageState.cs | 1 + src/Relayer/Pipeline/ReceivePipeline.cs | 3 +- src/Relayer/Telemetry/ConsumeLog.cs | 40 ++ src/Relayer/Telemetry/EndpointTelemetry.cs | 80 ++++ .../Telemetry/EndpointTelemetryOptions.cs | 20 + .../Telemetry/RelayerInstrumentation.cs | 67 +++ src/Relayer/Telemetry/RelayerTelemetry.cs | 6 + tests/Relayer.AotSmoke/Program.cs | 12 +- tests/Relayer.Tests/TelemetryTests.cs | 382 ++++++++++++++++++ 16 files changed, 843 insertions(+), 7 deletions(-) create mode 100644 benchmarks/Relayer.Benchmarks/TelemetryBenchmarks.cs create mode 100644 docs/telemetry.md create mode 100644 src/Relayer/Telemetry/ConsumeLog.cs create mode 100644 src/Relayer/Telemetry/EndpointTelemetry.cs create mode 100644 src/Relayer/Telemetry/EndpointTelemetryOptions.cs create mode 100644 src/Relayer/Telemetry/RelayerInstrumentation.cs create mode 100644 tests/Relayer.Tests/TelemetryTests.cs diff --git a/benchmarks/Relayer.Benchmarks/TelemetryBenchmarks.cs b/benchmarks/Relayer.Benchmarks/TelemetryBenchmarks.cs new file mode 100644 index 000000000..f28bf0cf8 --- /dev/null +++ b/benchmarks/Relayer.Benchmarks/TelemetryBenchmarks.cs @@ -0,0 +1,95 @@ +#pragma warning disable RLY001 // The benchmark explicitly registers its cached payload and serializer. +using System.Buffers; +using System.Diagnostics.Metrics; +using BenchmarkDotNet.Attributes; +using Microsoft.Extensions.DependencyInjection; +using Relayer.Serialization; + +namespace Relayer.Benchmarks; + +/// Measures telemetry's incremental CPU and allocation cost with identical DI/serializer work in each case. +[MemoryDiagnoser] +public class TelemetryBenchmarks +{ + private ServiceProvider _provider = null!; + private ConsumePipeline _baseline = null!; + private ConsumePipeline _instrumented = null!; + private MeterListener? _listener; + private EndpointTelemetry _endpoint = null!; + private ConsumeMessage _message; + + [Params(false, true)] + public bool ListenerAttached { get; set; } + + [GlobalSetup] + public void Setup() + { + var services = new ServiceCollection(); + services.AddSingleton(); + services.AddRelayer(r => { r.MessageTypes.Add("benchmark.payload"); r.Handler(); }); + _provider = services.BuildServiceProvider(); + var instrumentation = _provider.GetRequiredService(); + _endpoint = instrumentation.CreateEndpoint(new() + { + System = "kafka", Destination = "orders", ConsumerGroup = "billing", Subscription = "subscription", + ServerAddress = "localhost", ServerPort = 9092, + }); + if (ListenerAttached) + { + _listener = new MeterListener + { + InstrumentPublished = (instrument, listener) => + { + if (ReferenceEquals(instrument.Meter.Scope, instrumentation)) listener.EnableMeasurementEvents(instrument); + }, + }; + _listener.SetMeasurementEventCallback(static (_, _, _, _) => { }); + _listener.SetMeasurementEventCallback(static (_, _, _, _) => { }); + _listener.Start(); + } + _baseline = Builder().Build(1); + _instrumented = Builder().Telemetry(_endpoint).Build(1); + _message = new() { MessageId = "benchmark", MessageType = new("benchmark.payload", 1), Body = default }; + } + + private ConsumePipelineBuilder Builder() => new ConsumePipelineBuilder(_provider.GetRequiredService(), + _provider.GetRequiredService(), new Serializer(), static (_, error, _) => ValueTask.FromException(error)) + .Handler(_provider.GetRequiredService().GetHandler()); + + [Benchmark(Baseline = true)] + public async ValueTask ConsumerWithoutTelemetry() + { + using var context = _baseline.RentContext(_message); + await _baseline.ProcessAsync(context).ConfigureAwait(false); + } + + [Benchmark] + public async ValueTask ConsumerWithTelemetry() + { + using var context = _instrumented.RentContext(_message); + await _instrumented.ProcessAsync(context).ConfigureAwait(false); + } + + [Benchmark] + public void FailureMeasurement() => _endpoint.RecordDuration(TimeSpan.FromMilliseconds(1), failed: true); + + [GlobalCleanup] + public void Cleanup() + { + _listener?.Dispose(); + _provider.Dispose(); + } + + public sealed class Payload; + public sealed class Handler : IHandler + { + public ValueTask HandleAsync(Payload message, MessageContext context, CancellationToken cancellationToken) => default; + } + private sealed class Serializer : IMessageSerializer + { + private readonly Payload _payload = new(); + public string ContentType => "benchmark/cached"; + public T Deserialize(ReadOnlySequence source) => (T)(object)_payload; + public void Serialize(T message, IBufferWriter destination) => throw new NotSupportedException(); + } +} diff --git a/docs/design.md b/docs/design.md index 84ef5f915..c04d34e9b 100644 --- a/docs/design.md +++ b/docs/design.md @@ -604,6 +604,8 @@ Attributes that only Relayer defines use the `relayer.` prefix and never the `me ### 8.4 Metrics +See [metrics and logging integration](telemetry.md) for the implemented transport-author call site and recording contracts. + Instruments from the semantic conventions, with the conventions' recommended histogram buckets given as instrument advice: | Instrument | Type | Unit | Measures | diff --git a/docs/telemetry.md b/docs/telemetry.md new file mode 100644 index 000000000..ae1eb8c3e --- /dev/null +++ b/docs/telemetry.md @@ -0,0 +1,40 @@ +# Metrics and logging + +`AddRelayer` registers a single DI-owned `RelayerInstrumentation`. Its meter is named `Relayer`; subscribe with your OpenTelemetry provider's `AddMeter(RelayerTelemetry.MeterName)`. `RelayerTelemetry.SchemaUrl` pins the semantic conventions version. No OpenTelemetry SDK dependency is needed in the library. + +Transport authors compose endpoint telemetry at startup, alongside generated dispatch. For example, after registering and freezing handlers: + +```csharp +var instrumentation = provider.GetRequiredService(); +var process = instrumentation.CreateEndpoint(new EndpointTelemetryOptions +{ + System = "servicebus", + Destination = "orders", + Subscription = "billing", + ServerAddress = "example.servicebus.windows.net", +}); + +var consumer = new ConsumePipelineBuilder( + provider.GetRequiredService(), + provider.GetRequiredService(), + provider.GetRequiredService(), + HandleFailureDurablyAsync) + .Handler(orderHandlerDescriptor) + .Telemetry(process) + .Settle(SettleNativeMessageAsync) + .Build(); +``` + +The settlement callback reads the transport's native feature and its disposition. It runs only after durable processing, failure handling and async scope disposal succeed. It must honor `SettledByHandler`, use the broker's native semantics, and record its native operation with a separate endpoint recorder (`OperationName = "complete"`, `"ack"`, `"commit"`, etc.). `context.Services` is unavailable after scope disposal. A settlement error propagates to the receive loop without re-entering failure handling. If settlement runs outside this callback, its duration cannot be included in the process metric. Amortized commits stay outside per-message processing, as design §8.2 requires. + +The consumer records one `messaging.client.consumed.messages` measurement per delivery and a `messaging.process.duration` measurement after settlement. Processing failures, including ones durably handled by the failure pipeline, mark the duration with `error.type = "_OTHER"`. Actual exception objects are retained in logs. This bounded fallback avoids runtime type lookups and message-derived metric dimensions. Cancellation that reaches the consume pipeline is recorded as a failed delivery; cancellation before receive adaptation starts is not a delivery. + +Other execution components use the same recorder methods: `RecordSent` counts messages attempted at the broker, including failed attempts, but never an outbox enqueue. `RecordDuration` selects the process histogram only for `OperationName = "process"`; other operations use the client-operation histogram. Durations and dispatch lag use seconds. Outbox dispatch, retry, inbox, circuit and transport implementations call the corresponding recorder only when the actual action occurs. The current core exposes those recording seams; it does not infer retries or dead-letter success from a classifier decision. `RecordConsumerLag` accepts the native client's lag calculation. Circuit values are 0 closed, 1 open and 2 half-open. + +Each recorder retains precomputed `TagList` values, including its failure tags. Tags include only declared system, operation, destination, group, subscription and broker address/port. Do not create recorders per message or use dynamic destination names, message IDs or keys. Both convention histograms publish the [pinned conventions' recommended bucket advice](https://github.com/open-telemetry/semantic-conventions/blob/v1.44.0/docs/messaging/messaging-metrics.md). + +The consumer reads the transport binding's CloudEvents time header only when `relayer.critical_time` has a listener. Invalid or missing timestamps produce no critical-time measurement. With logging and metrics disabled, optional headers remain unread and telemetry adds no per-delivery allocations. + +Generated error logs use category `Relayer.ConsumePipeline` and event ID 1. When Error logging is enabled for that category, the delivery scope carries `MessageId`, the stable wire `MessageType`, and `CorrelationId` from the optional `correlation-id` header. The scope covers handling, failure handling, disposal and settlement. Failures log the exception and the ambient activity's `TraceId` and `SpanId`; no activity is created by this metrics/logging integration. Raw malformed envelope fields remain loggable without bypassing the failure classifier. Native adapters can supply the optional correlation header through their lazy header binding. + +Health integration is tracked separately in #85; tracing in #13. See [design §8](design.md#8-observability) for their contracts. diff --git a/src/Relayer/Configuration/RelayerServiceCollectionExtensions.cs b/src/Relayer/Configuration/RelayerServiceCollectionExtensions.cs index 302e1e77e..fba256629 100644 --- a/src/Relayer/Configuration/RelayerServiceCollectionExtensions.cs +++ b/src/Relayer/Configuration/RelayerServiceCollectionExtensions.cs @@ -21,6 +21,7 @@ public static IServiceCollection AddRelayer(this IServiceCollection services, Ac } var builder = new RelayerBuilder(services); + services.TryAddSingleton(); configure(builder); builder.MessageTypes.Freeze(); builder.Handlers.Freeze(); diff --git a/src/Relayer/Pipeline/ConsumePipeline.cs b/src/Relayer/Pipeline/ConsumePipeline.cs index f986ca8cf..7aafe7bbd 100644 --- a/src/Relayer/Pipeline/ConsumePipeline.cs +++ b/src/Relayer/Pipeline/ConsumePipeline.cs @@ -1,8 +1,10 @@ using System.Collections.Frozen; +using System.Diagnostics; +using System.Globalization; using System.Runtime.CompilerServices; using System.Text; -using System.Globalization; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; namespace Relayer; @@ -20,15 +22,21 @@ public sealed class ConsumePipeline private readonly ConsumeDelegate _pipeline; private readonly DefaultMessageContext?[] _contexts; private readonly WireIdentity[] _wireIdentities; + private readonly EndpointTelemetry? _telemetry; + private readonly ConsumeDelegate? _settlement; + internal HeaderNames EnvelopeNames { get; } = new(); internal ConsumePipeline(IServiceScopeFactory scopes, FrozenDictionary dispatch, - IReadOnlyList middleware, ConsumeFailureDelegate failure, IFailureClassifier classifier, int capacity, FailurePipeline? failures) + IReadOnlyList middleware, ConsumeFailureDelegate failure, IFailureClassifier classifier, + int capacity, FailurePipeline? failures, EndpointTelemetry? telemetry, ConsumeDelegate? settlement) { _scopes = scopes; _failures = failures; _dispatch = dispatch; _failure = failure; _classifier = classifier; + _telemetry = telemetry; + _settlement = settlement; _contexts = new DefaultMessageContext[capacity]; _wireIdentities = new WireIdentity[dispatch.Count]; var identityIndex = 0; @@ -98,7 +106,7 @@ internal MessageType ResolveWireIdentity(WireString wire) private readonly record struct WireIdentity(MessageType Identity, string Text, byte[] Utf8); - /// Processes one delivery in a fresh async DI scope. Does not settle the native message. + /// Processes one delivery in a fresh async DI scope, then invokes the configured native settlement callback. /// Cancellation propagates. Failure-pipeline and scope-disposal errors propagate, preventing successful settlement. public ValueTask ProcessAsync(DefaultMessageContext context) { @@ -110,8 +118,18 @@ public ValueTask ProcessAsync(DefaultMessageContext context) [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] private async ValueTask ProcessCoreAsync(DefaultMessageContext context) { + var telemetry = _telemetry; + var start = telemetry is { DurationEnabled: true } ? Stopwatch.GetTimestamp() : 0; + Exception? failure = null; + IDisposable? logScope = null; try { + telemetry?.RecordConsumed(); + if (telemetry?.Logger.IsEnabled(LogLevel.Error) == true) + { + context.LogScope.Initialize(context); + logScope = telemetry.Logger.BeginScope(context.LogScope); + } context.CancellationToken.ThrowIfCancellationRequested(); var scope = new AsyncServiceScope(_scopes.CreateScope()); try @@ -127,6 +145,8 @@ private async ValueTask ProcessCoreAsync(DefaultMessageContext context) catch (OperationCanceledException) when (context.CancellationToken.IsCancellationRequested) { throw; } catch (Exception error) { + failure = error; + LogFailure(telemetry, error); await _failure(context, error, _classifier.Classify(error, context)).ConfigureAwait(false); } } @@ -135,10 +155,31 @@ private async ValueTask ProcessCoreAsync(DefaultMessageContext context) // Calling the struct directly avoids boxing it through IAsyncDisposable.ConfigureAwait. await scope.DisposeAsync().ConfigureAwait(false); } + context.ClearServices(); + if (_settlement is { } settle) await settle(context).ConfigureAwait(false); + } + catch (Exception error) + { + if (!ReferenceEquals(failure, error)) LogFailure(telemetry, error); + failure = error; + throw; } finally { - context.EndProcessing(); + try + { + if (start != 0) telemetry!.RecordDuration(Stopwatch.GetElapsedTime(start), failure is not null); + telemetry?.RecordCriticalTime(context); + } + finally + { + try { logScope?.Dispose(); } + finally + { + context.LogScope.Clear(); + context.EndProcessing(); + } + } } } @@ -224,6 +265,13 @@ private async ValueTask ProcessWithFailuresAsync(DefaultMessageContext context) } } + private static void LogFailure(EndpointTelemetry? telemetry, Exception error) + { + if (telemetry?.Logger.IsEnabled(LogLevel.Error) != true) return; + var activity = Activity.Current; + ConsumeLog.Failed(telemetry.Logger, error, activity?.TraceId.ToString(), activity?.SpanId.ToString()); + } + private static ValueTask InvokeHandlerAsync(MessageContext context) => ((DefaultMessageContext)context).Dispatch(context); internal void Return(DefaultMessageContext context) diff --git a/src/Relayer/Pipeline/ConsumePipelineBuilder.cs b/src/Relayer/Pipeline/ConsumePipelineBuilder.cs index 0011d1785..d9aa3a0f2 100644 --- a/src/Relayer/Pipeline/ConsumePipelineBuilder.cs +++ b/src/Relayer/Pipeline/ConsumePipelineBuilder.cs @@ -16,6 +16,8 @@ public sealed class ConsumePipelineBuilder private readonly Dictionary _dispatch = []; private readonly List _middleware = []; private bool _built; + private EndpointTelemetry? _telemetry; + private ConsumeDelegate? _settlement; /// Creates a consumer composer with an explicit failure pipeline. /// The failure delegate must finish durable failure handling before returning successfully. @@ -72,6 +74,30 @@ public ConsumePipelineBuilder Use(IConsumeMiddleware middleware) return this; } + /// Attaches this endpoint's process metrics and generated failure logging. + public ConsumePipelineBuilder Telemetry(EndpointTelemetry telemetry) + { + EnsureMutable(); + ArgumentNullException.ThrowIfNull(telemetry); + if (!telemetry.IsProcess) + throw new ArgumentException("A consumer requires an endpoint recorder with OperationName 'process'.", nameof(telemetry)); + _telemetry = telemetry; + return this; + } + + /// Runs native settlement after durable handling and async scope disposal, inside processing duration. + /// + /// Transports read their native feature and disposition from the context. Honor SettledByHandler without settling twice. + /// Exceptions propagate without re-entering failure handling. Context.Services is unavailable during settlement. + /// + public ConsumePipelineBuilder Settle(ConsumeDelegate settlement) + { + EnsureMutable(); + ArgumentNullException.ThrowIfNull(settlement); + _settlement = settlement; + return this; + } + /// Builds this consumer once. Size the context pool for its maximum concurrent deliveries. public ConsumePipeline Build(int contextPoolCapacity = 64) { @@ -82,7 +108,8 @@ public ConsumePipeline Build(int contextPoolCapacity = 64) throw new InvalidOperationException("Register at least one generated handler before building a consumer."); } _built = true; - return new ConsumePipeline(_scopes, _dispatch.ToFrozenDictionary(), _middleware, _failure, _classifier, contextPoolCapacity, _failures); + return new ConsumePipeline(_scopes, _dispatch.ToFrozenDictionary(), _middleware, _failure, _classifier, + contextPoolCapacity, _failures, _telemetry, _settlement); } private void EnsureMutable() diff --git a/src/Relayer/Pipeline/DefaultMessageContext.cs b/src/Relayer/Pipeline/DefaultMessageContext.cs index 8f0028368..ec8c61c3f 100644 --- a/src/Relayer/Pipeline/DefaultMessageContext.cs +++ b/src/Relayer/Pipeline/DefaultMessageContext.cs @@ -42,6 +42,21 @@ internal void InitializeAttempts() } internal void NextAttempt() => _attempt = checked(Attempt + 1); internal ConsumeDelegate Dispatch { get; set; } = null!; + internal ConsumeLogScope LogScope { get; } = new(); + internal HeaderNames EnvelopeNames => _receive?.EnvelopeNames ?? _owner.EnvelopeNames; + + internal void GetLogIdentity(out string? id, out string? type) + { + if (_receive is null) + { + id = _message.MessageId; + type = _message.MessageType.ToString(); + return; + } + // Logging must also work for malformed envelopes without trying to parse their required fields. + id = _receive.TryGetValue(EnvelopeNames.Id, out var rawId) ? rawId.ToString() : null; + type = _receive.TryGetValue(EnvelopeNames.Type, out var rawType) ? rawType.ToString() : null; + } internal void Initialize(in ConsumeMessage message, CancellationToken cancellationToken) { @@ -66,6 +81,7 @@ internal void BeginProcessing(ConsumePipeline owner) } internal void SetServices(IServiceProvider services) => _services = services; + internal void ClearServices() => _services = null; internal void EndProcessing() { diff --git a/src/Relayer/Pipeline/ReceiveMessageState.cs b/src/Relayer/Pipeline/ReceiveMessageState.cs index d8c8e37c9..8718d0b96 100644 --- a/src/Relayer/Pipeline/ReceiveMessageState.cs +++ b/src/Relayer/Pipeline/ReceiveMessageState.cs @@ -4,6 +4,7 @@ namespace Relayer; internal abstract class ReceiveMessageState : MessageHeaders { + internal abstract HeaderNames EnvelopeNames { get; } internal abstract string MessageId { get; } internal abstract MessageType MessageType { get; } internal abstract int Attempt { get; } diff --git a/src/Relayer/Pipeline/ReceivePipeline.cs b/src/Relayer/Pipeline/ReceivePipeline.cs index d20ea98df..9c11bdd8c 100644 --- a/src/Relayer/Pipeline/ReceivePipeline.cs +++ b/src/Relayer/Pipeline/ReceivePipeline.cs @@ -6,7 +6,7 @@ namespace Relayer; /// Feeds untouched native deliveries into a composed consumer and returns native settlement decisions. /// /// Compose once per consumer. Body and header storage must remain valid until processing completes. -/// This adapter does not settle messages or implement capability fallbacks. The configured failure delegate +/// This adapter invokes the consumer's optional native settlement callback; it does not implement capability fallbacks. The configured failure delegate /// sets NativeMessage<TIncoming>.Disposition after durable failure handling. Exceptions and cancellation /// propagate without returning a settlement decision. Size both pools for maximum concurrent deliveries. /// @@ -86,6 +86,7 @@ private void Return(State state) private sealed class State(ConsumePipeline consumer, HeaderNames names) : ReceiveMessageState { + internal override HeaderNames EnvelopeNames => names; private MessageHeaders _headers; private WireString _id; private string? _messageId; diff --git a/src/Relayer/Telemetry/ConsumeLog.cs b/src/Relayer/Telemetry/ConsumeLog.cs new file mode 100644 index 000000000..1b43f5502 --- /dev/null +++ b/src/Relayer/Telemetry/ConsumeLog.cs @@ -0,0 +1,40 @@ +using System.Collections; +using Microsoft.Extensions.Logging; + +namespace Relayer; + +internal static partial class ConsumeLog +{ + [LoggerMessage(1, LogLevel.Error, "Message processing failed. TraceId={TraceId} SpanId={SpanId}.")] + internal static partial void Failed(ILogger logger, Exception exception, string? traceId, string? spanId); +} + +// Each pooled context owns its scope state; it is never shared across concurrent deliveries. +internal sealed class ConsumeLogScope : IReadOnlyList> +{ + private string? _id; + private string? _type; + private string? _correlation; + public int Count => 3; + public KeyValuePair this[int index] => index switch + { + 0 => new("MessageId", _id), + 1 => new("MessageType", _type), + 2 => new("CorrelationId", _correlation), + _ => throw new ArgumentOutOfRangeException(nameof(index)), + }; + + internal void Initialize(DefaultMessageContext context) + { + context.GetLogIdentity(out _id, out _type); + _correlation = context.Headers.TryGetValue("correlation-id", out var value) ? value.ToString() : null; + } + + internal void Clear() => (_id, _type, _correlation) = (null, null, null); + public IEnumerator> GetEnumerator() + { + for (var i = 0; i < Count; i++) yield return this[i]; + } + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); + public override string ToString() => $"MessageId={_id} MessageType={_type} CorrelationId={_correlation}"; +} diff --git a/src/Relayer/Telemetry/EndpointTelemetry.cs b/src/Relayer/Telemetry/EndpointTelemetry.cs new file mode 100644 index 000000000..2775a4fac --- /dev/null +++ b/src/Relayer/Telemetry/EndpointTelemetry.cs @@ -0,0 +1,80 @@ +using System.Diagnostics; +using System.Diagnostics.Metrics; +using System.Globalization; +using System.Text; +using Microsoft.Extensions.Logging; + +namespace Relayer; + +/// An endpoint operation's allocation-free metric recorder. All dimensions are computed at startup. +/// +/// Failed measurements use the conventions' bounded error.type value _OTHER; logs preserve the actual exception. +/// Counters describe actual attempts/actions: do not count outbox enqueue as a send, or redelivery as immediate retry. +/// +public sealed class EndpointTelemetry +{ + private readonly RelayerInstrumentation _instruments; + private readonly TagList _tags; + private readonly TagList _failedTags; + private readonly Histogram _duration; + internal ILogger Logger { get; } + internal bool IsProcess { get; } + internal bool CriticalTimeEnabled => _instruments.CriticalTime.Enabled; + internal bool DurationEnabled => _duration.Enabled; + + internal EndpointTelemetry(RelayerInstrumentation instruments, EndpointTelemetryOptions options, ILogger logger) + { + _instruments = instruments; + Logger = logger; + IsProcess = options.OperationName == "process"; + _duration = IsProcess ? instruments.ProcessDuration : instruments.OperationDuration; + _tags.Add("messaging.system", options.System); + _tags.Add("messaging.operation.name", options.OperationName); + if (options.Destination is { } destination) _tags.Add("messaging.destination.name", destination); + if (options.ConsumerGroup is { } group) _tags.Add("messaging.consumer.group.name", group); + if (options.Subscription is { } subscription) _tags.Add("messaging.destination.subscription.name", subscription); + if (options.ServerAddress is { } address) _tags.Add("server.address", address); + if (options.ServerPort is { } port) _tags.Add("server.port", port); + // Seven constant tags plus error.type fit TagList's inline storage, including on the failure path. + _failedTags = _tags; + _failedTags.Add("error.type", "_OTHER"); + } + + /// Records process duration for process, or client operation duration for other operation names. + public void RecordDuration(TimeSpan duration, bool failed = false) => _duration.Record(duration.TotalSeconds, failed ? _failedTags : _tags); + /// Counts messages attempted at the broker, including failed send attempts. + public void RecordSent(long count = 1, bool failed = false) => _instruments.Sent.Add(count, failed ? _failedTags : _tags); + /// Counts native deliveries once, independently of immediate retries. + public void RecordConsumed(long count = 1) => _instruments.Consumed.Add(count, in _tags); + /// Records processing end minus CloudEvents creation time, in seconds. + public void RecordCriticalTime(TimeSpan elapsed) => _instruments.CriticalTime.Record(elapsed.TotalSeconds, in _tags); + /// Counts immediate in-process retries. + public void RecordRetry(long count = 1) => _instruments.Retries.Add(count, in _tags); + /// Counts messages durably dead-lettered. + public void RecordDeadLettered(long count = 1) => _instruments.DeadLettered.Add(count, in _tags); + /// Updates pending outbox messages; removal uses a negative delta. + public void AddOutboxPending(long delta) => _instruments.OutboxPending.Add(delta, in _tags); + /// Records dispatch time minus enqueue time, in seconds. + public void RecordDispatchLag(TimeSpan elapsed) => _instruments.DispatchLag.Record(elapsed.TotalSeconds, in _tags); + /// Counts inbox duplicates that were suppressed. + public void RecordInboxDuplicate(long count = 1) => _instruments.Duplicates.Add(count, in _tags); + /// Records native consumer lag. Kafka adapters reuse Dekaf's lag calculation. + public void RecordConsumerLag(long lag) => _instruments.ConsumerLag.Record(lag, in _tags); + /// Records circuit state: 0 closed, 1 open, 2 half-open. + public void RecordCircuitState(int state) => _instruments.CircuitState.Record(state, in _tags); + + internal void RecordCriticalTime(DefaultMessageContext context) + { + if (!CriticalTimeEnabled || !context.Headers.TryGetValue(context.EnvelopeNames.Time, out var time)) return; + Span buffer = stackalloc char[64]; + scoped ReadOnlySpan text = time.Text; + if (time.Text is null) + { + if (time.Utf8.Length > buffer.Length) return; + var length = Encoding.UTF8.GetChars(time.Utf8.Span, buffer); + text = buffer[..length]; + } + if (DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out var created)) + RecordCriticalTime(DateTimeOffset.UtcNow - created); + } +} diff --git a/src/Relayer/Telemetry/EndpointTelemetryOptions.cs b/src/Relayer/Telemetry/EndpointTelemetryOptions.cs new file mode 100644 index 000000000..dc0ca50ef --- /dev/null +++ b/src/Relayer/Telemetry/EndpointTelemetryOptions.cs @@ -0,0 +1,20 @@ +namespace Relayer; + +/// Declared, low-cardinality metric dimensions. Create one recorder per endpoint and operation at startup. +public sealed class EndpointTelemetryOptions +{ + /// The native messaging system, for example kafka, servicebus or relayer.inmemory. + public required string System { get; init; } + /// The system's operation name, for example process, send, complete or ack. + public string OperationName { get; init; } = "process"; + /// The declared destination. Do not supply a dynamic destination or message key. + public string? Destination { get; init; } + /// The declared consumer group, where applicable. + public string? ConsumerGroup { get; init; } + /// The declared subscription, where applicable. + public string? Subscription { get; init; } + /// The broker's known address, without reverse DNS lookup. + public string? ServerAddress { get; init; } + /// The broker's known port. + public int? ServerPort { get; init; } +} diff --git a/src/Relayer/Telemetry/RelayerInstrumentation.cs b/src/Relayer/Telemetry/RelayerInstrumentation.cs new file mode 100644 index 000000000..85f32bf6f --- /dev/null +++ b/src/Relayer/Telemetry/RelayerInstrumentation.cs @@ -0,0 +1,67 @@ +using System.Diagnostics.Metrics; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Relayer; + +/// Owns the application's Relayer meter. DI disposes it with the service provider. +/// Use the registered singleton across endpoints. Standalone callers must dispose their instance. +public sealed class RelayerInstrumentation : IDisposable +{ + private readonly Meter _meter; + private readonly ILogger _logger; + internal Histogram OperationDuration { get; } + internal Histogram ProcessDuration { get; } + internal Counter Sent { get; } + internal Counter Consumed { get; } + internal Histogram CriticalTime { get; } + internal Counter Retries { get; } + internal Counter DeadLettered { get; } + internal UpDownCounter OutboxPending { get; } + internal Histogram DispatchLag { get; } + internal Counter Duplicates { get; } + internal Gauge ConsumerLag { get; } + internal Gauge CircuitState { get; } + + /// Creates instrumentation with an optional application logger factory. + public RelayerInstrumentation(ILoggerFactory? loggerFactory = null) + { + _logger = loggerFactory?.CreateLogger() ?? NullLogger.Instance; + _meter = new Meter(new MeterOptions(RelayerTelemetry.MeterName) + { + TelemetrySchemaUrl = RelayerTelemetry.SchemaUrl, + Scope = this, + }); + // https://github.com/open-telemetry/semantic-conventions/blob/v1.44.0/docs/messaging/messaging-metrics.md + var advice = new InstrumentAdvice + { + HistogramBucketBoundaries = [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10], + }; + OperationDuration = _meter.CreateHistogram("messaging.client.operation.duration", "s", advice: advice); + ProcessDuration = _meter.CreateHistogram("messaging.process.duration", "s", advice: advice); + Sent = _meter.CreateCounter("messaging.client.sent.messages", "{message}"); + Consumed = _meter.CreateCounter("messaging.client.consumed.messages", "{message}"); + CriticalTime = _meter.CreateHistogram("relayer.critical_time", "s"); + Retries = _meter.CreateCounter("relayer.retries", "{retry}"); + DeadLettered = _meter.CreateCounter("relayer.dead_lettered", "{message}"); + OutboxPending = _meter.CreateUpDownCounter("relayer.outbox.pending", "{message}"); + DispatchLag = _meter.CreateHistogram("relayer.outbox.dispatch_lag", "s"); + Duplicates = _meter.CreateCounter("relayer.inbox.duplicates", "{message}"); + ConsumerLag = _meter.CreateGauge("relayer.consumer.lag", "{message}"); + CircuitState = _meter.CreateGauge("relayer.circuit.state"); + } + + /// Precomputes one operation's tags. Reuse the returned recorder concurrently across deliveries. + public EndpointTelemetry CreateEndpoint(EndpointTelemetryOptions options) + { + ArgumentNullException.ThrowIfNull(options); + ArgumentException.ThrowIfNullOrWhiteSpace(options.System); + ArgumentException.ThrowIfNullOrWhiteSpace(options.OperationName); + if (options.ServerPort is { } port) ArgumentOutOfRangeException.ThrowIfNegativeOrZero(port); + if (options.ServerPort > 65535) throw new ArgumentOutOfRangeException(nameof(options), "ServerPort must not exceed 65535."); + return new(this, options, _logger); + } + + /// Stops publishing every instrument owned by this instance. + public void Dispose() => _meter.Dispose(); +} diff --git a/src/Relayer/Telemetry/RelayerTelemetry.cs b/src/Relayer/Telemetry/RelayerTelemetry.cs index 260f50b76..b4015c5b7 100644 --- a/src/Relayer/Telemetry/RelayerTelemetry.cs +++ b/src/Relayer/Telemetry/RelayerTelemetry.cs @@ -8,4 +8,10 @@ public static class RelayerTelemetry /// The name. Add it with AddMeter("Relayer"). public const string MeterName = "Relayer"; + + /// The implemented OpenTelemetry semantic conventions version. + public const string SemanticConventionsVersion = "1.44.0"; + + /// The telemetry schema shared by Relayer's instrumentation. + public const string SchemaUrl = "https://opentelemetry.io/schemas/" + SemanticConventionsVersion; } diff --git a/tests/Relayer.AotSmoke/Program.cs b/tests/Relayer.AotSmoke/Program.cs index 2873722eb..ce805d00f 100644 --- a/tests/Relayer.AotSmoke/Program.cs +++ b/tests/Relayer.AotSmoke/Program.cs @@ -75,7 +75,17 @@ var consumer = new ConsumePipelineBuilder(provider.GetRequiredService(), provider.GetRequiredService(), serializer, static (_, error, _) => ValueTask.FromException(error)) - .Handler(orderDescriptor).Build(1); + .Handler(orderDescriptor) + .Telemetry(provider.GetRequiredService().CreateEndpoint(new() + { + System = "relayer.inmemory", Destination = "orders", + })) + .Settle(static context => + { + if (context.Features.Get>() is null) + throw new InvalidOperationException("Settlement lost its native feature."); + return default; + }).Build(1); var receive = new ReceivePipeline(consumer, new HeaderNames(), 1); var disposition = await receive.ProcessAsync(new(new ReadOnlySequence(buffer.WrittenMemory))); if (disposition.Kind != DispositionKind.Complete) diff --git a/tests/Relayer.Tests/TelemetryTests.cs b/tests/Relayer.Tests/TelemetryTests.cs new file mode 100644 index 000000000..6f288a267 --- /dev/null +++ b/tests/Relayer.Tests/TelemetryTests.cs @@ -0,0 +1,382 @@ +#pragma warning disable RLY001 // Pipeline fixtures explicitly register their primitive wire identity and cached serializer. +using System.Buffers; +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Diagnostics.Metrics; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Relayer.Serialization; + +namespace Relayer.Tests; + +public class TelemetryTests +{ + [Test] + public async Task Instruments_have_pinned_schema_units_types_and_bucket_advice() + { + using var instrumentation = new RelayerInstrumentation(); + using var capture = new Capture(instrumentation); + var expected = new Dictionary + { + ["messaging.client.operation.duration"] = (typeof(Histogram), "s"), + ["messaging.process.duration"] = (typeof(Histogram), "s"), + ["messaging.client.sent.messages"] = (typeof(Counter), "{message}"), + ["messaging.client.consumed.messages"] = (typeof(Counter), "{message}"), + ["relayer.critical_time"] = (typeof(Histogram), "s"), + ["relayer.retries"] = (typeof(Counter), "{retry}"), + ["relayer.dead_lettered"] = (typeof(Counter), "{message}"), + ["relayer.outbox.pending"] = (typeof(UpDownCounter), "{message}"), + ["relayer.outbox.dispatch_lag"] = (typeof(Histogram), "s"), + ["relayer.inbox.duplicates"] = (typeof(Counter), "{message}"), + ["relayer.consumer.lag"] = (typeof(Gauge), "{message}"), + ["relayer.circuit.state"] = (typeof(Gauge), null), + }; + await Assert.That(capture.Instruments.Count).IsEqualTo(expected.Count); + foreach (var (name, (type, unit)) in expected) + { + var instrument = capture.Instruments[name]; + await Assert.That(instrument.GetType()).IsEqualTo(type); + await Assert.That(instrument.Unit).IsEqualTo(unit); + await Assert.That(instrument.Meter.Name).IsEqualTo("Relayer"); + await Assert.That(instrument.Meter.TelemetrySchemaUrl).IsEqualTo(RelayerTelemetry.SchemaUrl); + } + foreach (var name in new[] { "messaging.client.operation.duration", "messaging.process.duration" }) + { + var histogram = (Histogram)capture.Instruments[name]; + await Assert.That(histogram.Advice!.HistogramBucketBoundaries!.SequenceEqual( + new double[] { .005, .01, .025, .05, .075, .1, .25, .5, .75, 1, 2.5, 5, 7.5, 10 })).IsTrue(); + } + } + + [Test] + public async Task Recorders_preserve_units_tags_and_error_isolation() + { + using var instrumentation = new RelayerInstrumentation(); + using var capture = new Capture(instrumentation); + var process = instrumentation.CreateEndpoint(Options()); + var send = instrumentation.CreateEndpoint(Options("send")); + var settle = instrumentation.CreateEndpoint(Options("ack")); + send.RecordSent(3, failed: true); + send.RecordSent(2); + send.RecordDuration(TimeSpan.FromMilliseconds(250), failed: true); + settle.RecordDuration(TimeSpan.FromSeconds(2)); + process.RecordDuration(TimeSpan.FromSeconds(3)); + process.RecordConsumed(); + process.RecordCriticalTime(TimeSpan.FromSeconds(4)); + process.RecordRetry(2); + process.RecordDeadLettered(); + send.AddOutboxPending(5); + send.AddOutboxPending(-2); + send.RecordDispatchLag(TimeSpan.FromSeconds(6)); + process.RecordInboxDuplicate(); + process.RecordConsumerLag(7); + process.RecordCircuitState(1); + + var values = capture.Values.ToArray(); + foreach (var value in values) + { + await Assert.That(value.Tags["messaging.system"]).IsEqualTo("kafka"); + await Assert.That(value.Tags["messaging.operation.name"]).IsNotNull(); + await Assert.That(value.Tags["messaging.destination.name"]).IsEqualTo("orders"); + await Assert.That(value.Tags["messaging.consumer.group.name"]).IsEqualTo("billing"); + await Assert.That(value.Tags["messaging.destination.subscription.name"]).IsEqualTo("subscription"); + await Assert.That(value.Tags["server.address"]).IsEqualTo("broker"); + await Assert.That(value.Tags["server.port"]).IsEqualTo(9092); + await Assert.That(value.Tags.Keys.Any(key => key.Contains("message.id") || key.Contains("key"))).IsFalse(); + } + await Assert.That(values[0].Number).IsEqualTo(3d); + await Assert.That(values[0].Tags["error.type"]).IsEqualTo("_OTHER"); + await Assert.That(values[1].Tags.ContainsKey("error.type")).IsFalse(); + await Assert.That(values[2].Number).IsEqualTo(.25); + await Assert.That(values[3].Tags["messaging.operation.name"]).IsEqualTo("ack"); + await Assert.That(values.Single(v => v.Name == "messaging.process.duration").Number).IsEqualTo(3d); + await Assert.That(values.Where(v => v.Name == "relayer.outbox.pending").Sum(v => v.Number)).IsEqualTo(3d); + await Assert.That(values.Single(v => v.Name == "relayer.outbox.dispatch_lag").Number).IsEqualTo(6d); + await Assert.That(values.Single(v => v.Name == "relayer.consumer.lag").Number).IsEqualTo(7d); + } + + [Test] + public async Task Processing_includes_async_settlement_and_counts_one_delivery() + { + await using var provider = Provider(); + var instrumentation = provider.GetRequiredService(); + using var capture = new Capture(instrumentation); + var settled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var pipeline = Builder(provider).Telemetry(instrumentation.CreateEndpoint(Options())).Settle(context => + { + if (context.Features.Get>()?.Message is null) throw new InvalidOperationException("Native delivery lost."); + entered.SetResult(); + return new(settled.Task); + }).Build(1); + var receive = new ReceivePipeline(pipeline, new HeaderNames("cloudEvents:"), 1); + var pending = receive.ProcessAsync(new Incoming()); + await entered.Task; + await Assert.That(capture.Values.Count(v => v.Name == "messaging.client.consumed.messages")).IsEqualTo(1); + await Assert.That(capture.Values.Any(v => v.Name == "messaging.process.duration")).IsFalse(); + settled.SetResult(); + await pending; + await Assert.That(capture.Values.Count(v => v.Name == "messaging.process.duration")).IsEqualTo(1); + await Assert.That(capture.Values.Single(v => v.Name == "messaging.process.duration").Number).IsGreaterThan(0d); + await Assert.That(capture.Values.Single(v => v.Name == "relayer.critical_time").Number).IsGreaterThanOrEqualTo(60d); + } + + [Test] + public async Task Handler_failure_logs_scoped_identity_and_trace_even_when_failure_handling_recovers() + { + var logger = new Logger(); + using var instrumentation = new RelayerInstrumentation(new LoggerFactory(logger)); + using var capture = new Capture(instrumentation); + await using var provider = Provider(); + var error = new InvalidOperationException("broken handler"); + provider.GetRequiredService().Handle = _ => ValueTask.FromException(error); + var settlements = 0; + var pipeline = Builder(provider).Telemetry(instrumentation.CreateEndpoint(Options())) + .Settle(_ => { settlements++; return default; }).Build(1); + using var activity = new Activity("test").Start(); + using var context = pipeline.RentContext(Message() with { Headers = new Headers() }); + await pipeline.ProcessAsync(context); + var entry = logger.Entries.Single(); + await Assert.That(entry.Exception).IsSameReferenceAs(error); + await Assert.That(entry.Scope["MessageId"]).IsEqualTo("delivery"); + await Assert.That(entry.Scope["MessageType"]).IsEqualTo("number;v=1"); + await Assert.That(entry.Scope["CorrelationId"]).IsEqualTo("conversation"); + await Assert.That(entry.State["TraceId"]).IsEqualTo(activity.TraceId.ToString()); + await Assert.That(entry.State["SpanId"]).IsEqualTo(activity.SpanId.ToString()); + await Assert.That(settlements).IsEqualTo(1); + await Assert.That(capture.Values.Single(v => v.Name == "messaging.process.duration").Tags["error.type"]).IsEqualTo("_OTHER"); + await Assert.That(logger.CurrentScope).IsNull(); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Settlement_is_skipped_after_failed_durability_and_settlement_errors_are_not_reclassified(bool failSettlement) + { + await using var provider = Provider(); + var instrumentation = provider.GetRequiredService(); + using var capture = new Capture(instrumentation); + var error = new ApplicationException("durability failed"); + var failures = 0; + var settlements = 0; + if (!failSettlement) provider.GetRequiredService().Handle = _ => ValueTask.FromException(new Exception("handler")); + var pipeline = Builder(provider, (_, _, _) => { failures++; return ValueTask.FromException(error); }) + .Telemetry(instrumentation.CreateEndpoint(Options())) + .Settle(_ => { settlements++; return ValueTask.FromException(error); }).Build(); + using var context = pipeline.RentContext(Message()); + await Assert.That(async () => await pipeline.ProcessAsync(context)).Throws(); + await Assert.That(failures).IsEqualTo(failSettlement ? 0 : 1); + await Assert.That(settlements).IsEqualTo(failSettlement ? 1 : 0); + await Assert.That(capture.Values.Single(v => v.Name == "messaging.process.duration").Tags["error.type"]).IsEqualTo("_OTHER"); + } + + [Test] + public async Task Disabled_listeners_and_logging_do_not_read_optional_headers_and_context_reuse_clears_scope() + { + await using var provider = Provider(); + var instrumentation = provider.GetRequiredService(); + var pipeline = Builder(provider).Telemetry(instrumentation.CreateEndpoint(Options())).Build(1); + for (var i = 0; i < 2; i++) + { + using var context = pipeline.RentContext(Message() with { Headers = new UnreadHeaders() }); + await pipeline.ProcessAsync(context); + await Assert.That(context.LogScope[0].Value).IsNull(); + } + } + + [Test] + public async Task Malformed_envelopes_still_log_and_count_delivery_without_logging_bypassing_failure_handling() + { + var logger = new Logger(); + using var instrumentation = new RelayerInstrumentation(new LoggerFactory(logger)); + using var capture = new Capture(instrumentation); + await using var provider = Provider(); + var failures = 0; + var pipeline = Builder(provider, (_, _, _) => { failures++; return default; }) + .Telemetry(instrumentation.CreateEndpoint(Options())).Build(); + var receive = new ReceivePipeline(pipeline, new HeaderNames("cloudEvents:")); + await receive.ProcessAsync(new Incoming { Type = null }); + await Assert.That(failures).IsEqualTo(1); + await Assert.That(logger.Entries.Single().Exception is MessageEnvelopeException).IsTrue(); + await Assert.That(capture.Values.Count(v => v.Name == "messaging.client.consumed.messages")).IsEqualTo(1); + } + + [Test] + public async Task Cancellation_is_counted_and_never_settled() + { + await using var provider = Provider(); + var instrumentation = provider.GetRequiredService(); + using var capture = new Capture(instrumentation); + var settlements = 0; + var pipeline = Builder(provider).Telemetry(instrumentation.CreateEndpoint(Options())) + .Settle(_ => { settlements++; return default; }).Build(); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + using var context = pipeline.RentContext(Message(), cancellation.Token); + await Assert.That(async () => await pipeline.ProcessAsync(context)).Throws(); + await Assert.That(settlements).IsEqualTo(0); + await Assert.That(capture.Values.Count(v => v.Name == "messaging.client.consumed.messages")).IsEqualTo(1); + } + + [Test] + public async Task Async_scope_disposal_finishes_before_settlement_and_its_services_are_unavailable() + { + var gate = new DisposalGate(); + await using var provider = Provider(services => services.AddScoped(_ => gate)); + provider.GetRequiredService().Handle = context => + { + _ = context.Services.GetRequiredService(); + return default; + }; + var settlements = 0; + var pipeline = Builder(provider).Settle(context => + { + try { _ = context.Services; } + catch (InvalidOperationException) { settlements++; return default; } + throw new InvalidOperationException("Disposed scope is still exposed."); + }).Build(); + using var context = pipeline.RentContext(Message()); + var pending = pipeline.ProcessAsync(context); + await gate.Entered.Task; + await Assert.That(settlements).IsEqualTo(0); + gate.Finished.SetResult(); + await pending; + await Assert.That(settlements).IsEqualTo(1); + } + + [Test] + public async Task Endpoint_configuration_fails_early_and_instrumentation_is_owned_by_each_provider() + { + await using var first = Provider(); + await using var second = Provider(); + var instrumentation = first.GetRequiredService(); + await Assert.That(instrumentation).IsSameReferenceAs(first.GetRequiredService()); + await Assert.That(instrumentation).IsNotSameReferenceAs(second.GetRequiredService()); + await Assert.That(() => instrumentation.CreateEndpoint(new() { System = " " })).Throws(); + await Assert.That(() => instrumentation.CreateEndpoint(new() { System = "kafka", ServerPort = 65536 })).Throws(); + await Assert.That(() => Builder(first).Telemetry(instrumentation.CreateEndpoint(Options("send")))).Throws(); + } + + private static EndpointTelemetryOptions Options(string operation = "process") => new() + { + System = "kafka", OperationName = operation, Destination = "orders", ConsumerGroup = "billing", + Subscription = "subscription", ServerAddress = "broker", ServerPort = 9092, + }; + + private static ServiceProvider Provider(Action? configure = null) + { + var services = new ServiceCollection(); + services.AddSingleton(); + services.AddSingleton(); + services.AddRelayer(r => { r.MessageTypes.Add("number"); r.Handler(); }); + configure?.Invoke(services); + return services.BuildServiceProvider(); + } + + private static ConsumePipelineBuilder Builder(ServiceProvider provider, ConsumeFailureDelegate? failure = null) => + new ConsumePipelineBuilder(provider.GetRequiredService(), provider.GetRequiredService(), + new Serializer(), failure ?? (static (_, _, _) => default)) + .Handler(provider.GetRequiredService().GetHandler()); + + private static ConsumeMessage Message() => new() { MessageId = "delivery", MessageType = new("number", 1), Body = default }; + public sealed class Control { public ConsumeDelegate? Handle { get; set; } } + public sealed class Handler(Control control) : IHandler + { + public ValueTask HandleAsync(int message, MessageContext context, CancellationToken cancellationToken) => control.Handle?.Invoke(context) ?? default; + } + private sealed class Serializer : IMessageSerializer + { + public string ContentType => "test/cached"; + public T Deserialize(ReadOnlySequence source) => (T)(object)1; + public void Serialize(T message, IBufferWriter destination) => throw new NotSupportedException(); + } + private sealed class Headers : MessageHeaders + { + public override bool TryGetValue(string name, out WireString value) + { + value = name == "correlation-id" ? new WireString("conversation") : default; + return !value.IsEmpty; + } + } + private sealed class UnreadHeaders : MessageHeaders + { + public override bool TryGetValue(string name, out WireString value) => throw new InvalidOperationException("Optional headers were read."); + } + private sealed class DisposalGate : IAsyncDisposable + { + internal TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal TaskCompletionSource Finished { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public ValueTask DisposeAsync() + { + Entered.SetResult(); + return new(Finished.Task); + } + } + private sealed class Incoming + { + public string? Type { get; init; } = "number;v=1"; + public string Time { get; } = DateTimeOffset.UtcNow.AddMinutes(-1).ToString("O"); + } + private readonly struct Binding : IMessageBinding + { + public static ReadOnlySequence GetBody(Incoming message) => default; + public static int? GetDeliveryCount(Incoming message) => 1; + public static bool TryGetHeader(Incoming message, string name, out WireString value) + { + value = name switch + { + "cloudEvents:type" => message.Type is { } type ? new(type) : default, + "cloudEvents:id" => new("native"), + "cloudEvents:time" => new(message.Time), + _ => default, + }; + return !value.IsEmpty; + } + } + + private sealed record Measurement(string Name, double Number, Dictionary Tags); + private sealed class Capture : IDisposable + { + private readonly MeterListener _listener = new(); + internal Dictionary Instruments { get; } = []; + internal ConcurrentQueue Values { get; } = new(); + internal Capture(RelayerInstrumentation instrumentation) + { + _listener.InstrumentPublished = (instrument, listener) => + { + if (!ReferenceEquals(instrument.Meter.Scope, instrumentation)) return; + Instruments.Add(instrument.Name, instrument); + listener.EnableMeasurementEvents(instrument); + }; + _listener.SetMeasurementEventCallback((instrument, value, tags, _) => Add(instrument, value, tags)); + _listener.SetMeasurementEventCallback((instrument, value, tags, _) => Add(instrument, value, tags)); + _listener.SetMeasurementEventCallback((instrument, value, tags, _) => Add(instrument, value, tags)); + _listener.Start(); + } + private void Add(Instrument instrument, double value, ReadOnlySpan> tags) => + Values.Enqueue(new(instrument.Name, value, tags.ToArray().ToDictionary())); + public void Dispose() => _listener.Dispose(); + } + + private sealed record Entry(Exception? Exception, Dictionary Scope, Dictionary State); + private sealed class Logger : ILogger + { + internal IReadOnlyList>? CurrentScope { get; private set; } + internal List Entries { get; } = []; + public bool IsEnabled(LogLevel logLevel) => true; + public IDisposable? BeginScope(TState state) where TState : notnull + { + CurrentScope = (IReadOnlyList>)(object)state; + return new Scope(this); + } + public void Log(LogLevel level, EventId id, TState state, Exception? error, Func formatter) => + Entries.Add(new(error, CurrentScope!.ToDictionary(), ((IEnumerable>)(object)state!).ToDictionary())); + private sealed class Scope(Logger owner) : IDisposable { public void Dispose() => owner.CurrentScope = null; } + } + private sealed class LoggerFactory(Logger logger) : ILoggerFactory + { + public ILogger CreateLogger(string categoryName) => logger; + public void AddProvider(ILoggerProvider provider) => throw new NotSupportedException(); + public void Dispose() { } + } +} From 69313ebe810a0308c704602eb99de476862b3605 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:52:38 +0000 Subject: [PATCH 2/8] fix: suppress expected consume cancellation error logs (#84) --- docs/telemetry.md | 2 +- src/Relayer/Pipeline/ConsumePipeline.cs | 4 +- tests/Relayer.Tests/TelemetryTests.cs | 56 +++++++++++++++++++++---- 3 files changed, 53 insertions(+), 9 deletions(-) diff --git a/docs/telemetry.md b/docs/telemetry.md index ae1eb8c3e..67f9a1931 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -35,6 +35,6 @@ Each recorder retains precomputed `TagList` values, including its failure tags. The consumer reads the transport binding's CloudEvents time header only when `relayer.critical_time` has a listener. Invalid or missing timestamps produce no critical-time measurement. With logging and metrics disabled, optional headers remain unread and telemetry adds no per-delivery allocations. -Generated error logs use category `Relayer.ConsumePipeline` and event ID 1. When Error logging is enabled for that category, the delivery scope carries `MessageId`, the stable wire `MessageType`, and `CorrelationId` from the optional `correlation-id` header. The scope covers handling, failure handling, disposal and settlement. Failures log the exception and the ambient activity's `TraceId` and `SpanId`; no activity is created by this metrics/logging integration. Raw malformed envelope fields remain loggable without bypassing the failure classifier. Native adapters can supply the optional correlation header through their lazy header binding. +Generated error logs use category `Relayer.ConsumePipeline` and event ID 1. When Error logging is enabled for that category, the delivery scope carries `MessageId`, the stable wire `MessageType`, and `CorrelationId` from the optional `correlation-id` header. The scope covers handling, failure handling, disposal and settlement. Cancellation with the delivery token canceled propagates without an Error log, while unrelated cancellation failures are logged normally. Failures log the exception and the ambient activity's `TraceId` and `SpanId`; no activity is created by this metrics/logging integration. Raw malformed envelope fields remain loggable without bypassing the failure classifier. Native adapters can supply the optional correlation header through their lazy header binding. Health integration is tracked separately in #85; tracing in #13. See [design §8](design.md#8-observability) for their contracts. diff --git a/src/Relayer/Pipeline/ConsumePipeline.cs b/src/Relayer/Pipeline/ConsumePipeline.cs index 7aafe7bbd..44dbbf95b 100644 --- a/src/Relayer/Pipeline/ConsumePipeline.cs +++ b/src/Relayer/Pipeline/ConsumePipeline.cs @@ -160,7 +160,9 @@ private async ValueTask ProcessCoreAsync(DefaultMessageContext context) } catch (Exception error) { - if (!ReferenceEquals(failure, error)) LogFailure(telemetry, error); + if (!ReferenceEquals(failure, error) && + (error is not OperationCanceledException || !context.CancellationToken.IsCancellationRequested)) + LogFailure(telemetry, error); failure = error; throw; } diff --git a/tests/Relayer.Tests/TelemetryTests.cs b/tests/Relayer.Tests/TelemetryTests.cs index 6f288a267..b4fdf7cef 100644 --- a/tests/Relayer.Tests/TelemetryTests.cs +++ b/tests/Relayer.Tests/TelemetryTests.cs @@ -202,20 +202,62 @@ public async Task Malformed_envelopes_still_log_and_count_delivery_without_loggi } [Test] - public async Task Cancellation_is_counted_and_never_settled() + [Arguments("before")] + [Arguments("handler")] + [Arguments("settlement")] + public async Task Delivery_cancellation_is_counted_without_error_logging(string stage) { + var logger = new Logger(); + using var instrumentation = new RelayerInstrumentation(new LoggerFactory(logger)); await using var provider = Provider(); - var instrumentation = provider.GetRequiredService(); using var capture = new Capture(instrumentation); - var settlements = 0; - var pipeline = Builder(provider).Telemetry(instrumentation.CreateEndpoint(Options())) - .Settle(_ => { settlements++; return default; }).Build(); using var cancellation = new CancellationTokenSource(); - cancellation.Cancel(); + provider.GetRequiredService().Handle = context => + { + if (stage == "handler") + { + cancellation.Cancel(); + context.CancellationToken.ThrowIfCancellationRequested(); + } + return default; + }; + var settlements = 0; + var failures = 0; + var pipeline = Builder(provider, (_, _, _) => { failures++; return default; }) + .Telemetry(instrumentation.CreateEndpoint(Options())) + .Settle(context => + { + settlements++; + cancellation.Cancel(); + context.CancellationToken.ThrowIfCancellationRequested(); + return default; + }).Build(); + if (stage == "before") cancellation.Cancel(); using var context = pipeline.RentContext(Message(), cancellation.Token); await Assert.That(async () => await pipeline.ProcessAsync(context)).Throws(); - await Assert.That(settlements).IsEqualTo(0); + await Assert.That(settlements).IsEqualTo(stage == "settlement" ? 1 : 0); + await Assert.That(failures).IsEqualTo(0); + await Assert.That(logger.Entries.Count).IsEqualTo(0); + await Assert.That(logger.CurrentScope).IsNull(); await Assert.That(capture.Values.Count(v => v.Name == "messaging.client.consumed.messages")).IsEqualTo(1); + await Assert.That(capture.Values.Single(v => v.Name == "messaging.process.duration").Tags["error.type"]).IsEqualTo("_OTHER"); + } + + [Test] + public async Task Cancellation_without_delivery_cancellation_is_logged_and_classified() + { + var logger = new Logger(); + using var instrumentation = new RelayerInstrumentation(new LoggerFactory(logger)); + await using var provider = Provider(); + var error = new OperationCanceledException("Handler's independent operation was canceled."); + provider.GetRequiredService().Handle = _ => ValueTask.FromException(error); + var failures = 0; + var pipeline = Builder(provider, (_, _, _) => { failures++; return default; }) + .Telemetry(instrumentation.CreateEndpoint(Options())).Build(); + using var context = pipeline.RentContext(Message()); + await pipeline.ProcessAsync(context); + await Assert.That(failures).IsEqualTo(1); + await Assert.That(logger.Entries.Single().Exception).IsSameReferenceAs(error); } [Test] From f41db47bee9a153f1be35daf43ef747d1c5bc24f Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 11:59:54 +0000 Subject: [PATCH 3/8] fix: bind correlation headers and exclude expected cancellation errors (#84) --- docs/telemetry.md | 10 +++- src/Relayer/Envelope/HeaderNames.cs | 3 ++ src/Relayer/Pipeline/ConsumePipeline.cs | 5 +- src/Relayer/Telemetry/ConsumeLog.cs | 2 +- tests/Relayer.Tests/TelemetryTests.cs | 65 +++++++++++++++++++++---- 5 files changed, 69 insertions(+), 16 deletions(-) diff --git a/docs/telemetry.md b/docs/telemetry.md index 67f9a1931..c83a7742e 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -27,7 +27,7 @@ var consumer = new ConsumePipelineBuilder( The settlement callback reads the transport's native feature and its disposition. It runs only after durable processing, failure handling and async scope disposal succeed. It must honor `SettledByHandler`, use the broker's native semantics, and record its native operation with a separate endpoint recorder (`OperationName = "complete"`, `"ack"`, `"commit"`, etc.). `context.Services` is unavailable after scope disposal. A settlement error propagates to the receive loop without re-entering failure handling. If settlement runs outside this callback, its duration cannot be included in the process metric. Amortized commits stay outside per-message processing, as design §8.2 requires. -The consumer records one `messaging.client.consumed.messages` measurement per delivery and a `messaging.process.duration` measurement after settlement. Processing failures, including ones durably handled by the failure pipeline, mark the duration with `error.type = "_OTHER"`. Actual exception objects are retained in logs. This bounded fallback avoids runtime type lookups and message-derived metric dimensions. Cancellation that reaches the consume pipeline is recorded as a failed delivery; cancellation before receive adaptation starts is not a delivery. +The consumer records one `messaging.client.consumed.messages` measurement per delivery and a `messaging.process.duration` measurement after settlement. Processing failures, including ones durably handled by the failure pipeline, mark the duration with `error.type = "_OTHER"`. Actual exception objects are retained in logs. This bounded fallback avoids runtime type lookups and message-derived metric dimensions. Delivery-token cancellation still counts as a delivery and records duration, but does not add `error.type`. If handling already failed before settlement is canceled, the duration retains that earlier failure. Cancellation before receive adaptation starts is not a delivery. Other execution components use the same recorder methods: `RecordSent` counts messages attempted at the broker, including failed attempts, but never an outbox enqueue. `RecordDuration` selects the process histogram only for `OperationName = "process"`; other operations use the client-operation histogram. Durations and dispatch lag use seconds. Outbox dispatch, retry, inbox, circuit and transport implementations call the corresponding recorder only when the actual action occurs. The current core exposes those recording seams; it does not infer retries or dead-letter success from a classifier decision. `RecordConsumerLag` accepts the native client's lag calculation. Circuit values are 0 closed, 1 open and 2 half-open. @@ -35,6 +35,12 @@ Each recorder retains precomputed `TagList` values, including its failure tags. The consumer reads the transport binding's CloudEvents time header only when `relayer.critical_time` has a listener. Invalid or missing timestamps produce no critical-time measurement. With logging and metrics disabled, optional headers remain unread and telemetry adds no per-delivery allocations. -Generated error logs use category `Relayer.ConsumePipeline` and event ID 1. When Error logging is enabled for that category, the delivery scope carries `MessageId`, the stable wire `MessageType`, and `CorrelationId` from the optional `correlation-id` header. The scope covers handling, failure handling, disposal and settlement. Cancellation with the delivery token canceled propagates without an Error log, while unrelated cancellation failures are logged normally. Failures log the exception and the ambient activity's `TraceId` and `SpanId`; no activity is created by this metrics/logging integration. Raw malformed envelope fields remain loggable without bypassing the failure classifier. Native adapters can supply the optional correlation header through their lazy header binding. +Generated error logs use category `Relayer.ConsumePipeline` and event ID 1. When Error logging is enabled for that category, the delivery scope carries `MessageId`, the stable wire `MessageType`, and `CorrelationId` from the optional CloudEvents `correlationid` extension (`ce_correlationid` or `cloudEvents:correlationid`, resolved through `HeaderNames.CorrelationId`). The scope covers handling, failure handling, disposal and settlement. Cancellation with the delivery token canceled propagates without an Error log, while unrelated cancellation failures are logged normally. Failures log the exception and the ambient activity's `TraceId` and `SpanId`; no activity is created by this metrics/logging integration. Raw malformed envelope fields remain loggable without bypassing the failure classifier. Producers opt into correlation by writing the extension through their native header writer using `names.CorrelationId`; the envelope writer does not invent a correlation ID. Native adapters expose that header through their lazy binding, including messages from non-Relayer producers. For example, after writing the envelope: + +```csharp +NativeHeaderWriter.SetHeader(nativeMessage, names.CorrelationId, correlationId); +``` + +Scope state belongs to the pooled delivery context. Logging providers must snapshot scope values synchronously during logging before queuing an entry for asynchronous export. Health integration is tracked separately in #85; tracing in #13. See [design §8](design.md#8-observability) for their contracts. diff --git a/src/Relayer/Envelope/HeaderNames.cs b/src/Relayer/Envelope/HeaderNames.cs index 07bbe05bb..7002aecad 100644 --- a/src/Relayer/Envelope/HeaderNames.cs +++ b/src/Relayer/Envelope/HeaderNames.cs @@ -12,6 +12,7 @@ public HeaderNames(string prefix = "ce_") Source = prefix + "source"; Time = prefix + "time"; SpecVersion = prefix + "specversion"; + CorrelationId = prefix + "correlationid"; } /// The event ID header. @@ -24,6 +25,8 @@ public HeaderNames(string prefix = "ce_") public string Time { get; } /// The CloudEvents version header. public string SpecVersion { get; } + /// The optional CloudEvents correlationid extension header. + public string CorrelationId { get; } /// The W3C trace parent header. public string TraceParent => "traceparent"; /// The W3C trace state header. diff --git a/src/Relayer/Pipeline/ConsumePipeline.cs b/src/Relayer/Pipeline/ConsumePipeline.cs index 44dbbf95b..087404118 100644 --- a/src/Relayer/Pipeline/ConsumePipeline.cs +++ b/src/Relayer/Pipeline/ConsumePipeline.cs @@ -158,11 +158,10 @@ private async ValueTask ProcessCoreAsync(DefaultMessageContext context) context.ClearServices(); if (_settlement is { } settle) await settle(context).ConfigureAwait(false); } + catch (OperationCanceledException) when (context.CancellationToken.IsCancellationRequested) { throw; } catch (Exception error) { - if (!ReferenceEquals(failure, error) && - (error is not OperationCanceledException || !context.CancellationToken.IsCancellationRequested)) - LogFailure(telemetry, error); + if (!ReferenceEquals(failure, error)) LogFailure(telemetry, error); failure = error; throw; } diff --git a/src/Relayer/Telemetry/ConsumeLog.cs b/src/Relayer/Telemetry/ConsumeLog.cs index 1b43f5502..498e1cefb 100644 --- a/src/Relayer/Telemetry/ConsumeLog.cs +++ b/src/Relayer/Telemetry/ConsumeLog.cs @@ -27,7 +27,7 @@ internal sealed class ConsumeLogScope : IReadOnlyList (_id, _type, _correlation) = (null, null, null); diff --git a/tests/Relayer.Tests/TelemetryTests.cs b/tests/Relayer.Tests/TelemetryTests.cs index b4fdf7cef..350771be7 100644 --- a/tests/Relayer.Tests/TelemetryTests.cs +++ b/tests/Relayer.Tests/TelemetryTests.cs @@ -148,6 +148,45 @@ public async Task Handler_failure_logs_scoped_identity_and_trace_even_when_failu await Assert.That(logger.CurrentScope).IsNull(); } + [Test] + [Arguments("ce_", false)] + [Arguments("ce_", true)] + [Arguments("cloudEvents:", false)] + [Arguments("cloudEvents:", true)] + public async Task Correlation_scope_reads_the_native_binding_and_clears_on_reuse(string prefix, bool utf8) + { + var logger = new Logger(); + using var instrumentation = new RelayerInstrumentation(new LoggerFactory(logger)); + await using var provider = Provider(); + provider.GetRequiredService().Handle = _ => ValueTask.FromException(new Exception("handler")); + var pipeline = Builder(provider).Telemetry(instrumentation.CreateEndpoint(Options())).Build(1); + var receive = new ReceivePipeline(pipeline, new HeaderNames(prefix), 1); + await receive.ProcessAsync(new Incoming { Prefix = prefix, CorrelationId = "conversation", Utf8 = utf8 }); + await receive.ProcessAsync(new Incoming { Prefix = prefix, Utf8 = utf8 }); + await Assert.That(logger.Entries[0].Scope["CorrelationId"]).IsEqualTo("conversation"); + await Assert.That(logger.Entries[1].Scope["CorrelationId"]).IsNull(); + } + + [Test] + public async Task Settlement_cancellation_preserves_an_earlier_handler_failure_metric() + { + await using var provider = Provider(); + var instrumentation = provider.GetRequiredService(); + using var capture = new Capture(instrumentation); + using var cancellation = new CancellationTokenSource(); + provider.GetRequiredService().Handle = _ => ValueTask.FromException(new Exception("handler")); + var pipeline = Builder(provider).Telemetry(instrumentation.CreateEndpoint(Options())) + .Settle(context => + { + cancellation.Cancel(); + context.CancellationToken.ThrowIfCancellationRequested(); + return default; + }).Build(); + using var context = pipeline.RentContext(Message(), cancellation.Token); + await Assert.That(async () => await pipeline.ProcessAsync(context)).Throws(); + await Assert.That(capture.Values.Single(v => v.Name == "messaging.process.duration").Tags["error.type"]).IsEqualTo("_OTHER"); + } + [Test] [Arguments(false)] [Arguments(true)] @@ -205,7 +244,7 @@ public async Task Malformed_envelopes_still_log_and_count_delivery_without_loggi [Arguments("before")] [Arguments("handler")] [Arguments("settlement")] - public async Task Delivery_cancellation_is_counted_without_error_logging(string stage) + public async Task Delivery_cancellation_is_counted_without_error_logging_or_error_metric(string stage) { var logger = new Logger(); using var instrumentation = new RelayerInstrumentation(new LoggerFactory(logger)); @@ -240,7 +279,7 @@ public async Task Delivery_cancellation_is_counted_without_error_logging(string await Assert.That(logger.Entries.Count).IsEqualTo(0); await Assert.That(logger.CurrentScope).IsNull(); await Assert.That(capture.Values.Count(v => v.Name == "messaging.client.consumed.messages")).IsEqualTo(1); - await Assert.That(capture.Values.Single(v => v.Name == "messaging.process.duration").Tags["error.type"]).IsEqualTo("_OTHER"); + await Assert.That(capture.Values.Single(v => v.Name == "messaging.process.duration").Tags.ContainsKey("error.type")).IsFalse(); } [Test] @@ -249,6 +288,7 @@ public async Task Cancellation_without_delivery_cancellation_is_logged_and_class var logger = new Logger(); using var instrumentation = new RelayerInstrumentation(new LoggerFactory(logger)); await using var provider = Provider(); + using var capture = new Capture(instrumentation); var error = new OperationCanceledException("Handler's independent operation was canceled."); provider.GetRequiredService().Handle = _ => ValueTask.FromException(error); var failures = 0; @@ -258,6 +298,7 @@ public async Task Cancellation_without_delivery_cancellation_is_logged_and_class await pipeline.ProcessAsync(context); await Assert.That(failures).IsEqualTo(1); await Assert.That(logger.Entries.Single().Exception).IsSameReferenceAs(error); + await Assert.That(capture.Values.Single(v => v.Name == "messaging.process.duration").Tags["error.type"]).IsEqualTo("_OTHER"); } [Test] @@ -336,7 +377,7 @@ private sealed class Headers : MessageHeaders { public override bool TryGetValue(string name, out WireString value) { - value = name == "correlation-id" ? new WireString("conversation") : default; + value = name == "ce_correlationid" ? new WireString("conversation") : default; return !value.IsEmpty; } } @@ -357,6 +398,9 @@ public ValueTask DisposeAsync() private sealed class Incoming { public string? Type { get; init; } = "number;v=1"; + public string Prefix { get; init; } = "cloudEvents:"; + public string? CorrelationId { get; init; } + public bool Utf8 { get; init; } public string Time { get; } = DateTimeOffset.UtcNow.AddMinutes(-1).ToString("O"); } private readonly struct Binding : IMessageBinding @@ -365,13 +409,14 @@ private sealed class Incoming public static int? GetDeliveryCount(Incoming message) => 1; public static bool TryGetHeader(Incoming message, string name, out WireString value) { - value = name switch - { - "cloudEvents:type" => message.Type is { } type ? new(type) : default, - "cloudEvents:id" => new("native"), - "cloudEvents:time" => new(message.Time), - _ => default, - }; + string? text = null; + if (name == message.Prefix + "type") text = message.Type; + else if (name == message.Prefix + "id") text = "native"; + else if (name == message.Prefix + "time") text = message.Time; + else if (name == message.Prefix + "correlationid") text = message.CorrelationId; + value = default; + if (text is not null) + value = message.Utf8 ? new(System.Text.Encoding.UTF8.GetBytes(text)) : new(text); return !value.IsEmpty; } } From 7473c4763c43f601e74496949e6e2a8fd44053cc Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:08:41 +0000 Subject: [PATCH 4/8] fix: defer consume log identity formatting for #84 --- .../Relayer.Benchmarks/TelemetryBenchmarks.cs | 45 ++++++++++++++ docs/telemetry.md | 2 +- src/Relayer/Pipeline/ConsumePipeline.cs | 9 +++ src/Relayer/Pipeline/DefaultMessageContext.cs | 20 +++---- src/Relayer/Telemetry/ConsumeLog.cs | 23 ++++--- tests/Relayer.Tests/TelemetryTests.cs | 60 ++++++++++++++++++- 6 files changed, 137 insertions(+), 22 deletions(-) diff --git a/benchmarks/Relayer.Benchmarks/TelemetryBenchmarks.cs b/benchmarks/Relayer.Benchmarks/TelemetryBenchmarks.cs index f28bf0cf8..daf123333 100644 --- a/benchmarks/Relayer.Benchmarks/TelemetryBenchmarks.cs +++ b/benchmarks/Relayer.Benchmarks/TelemetryBenchmarks.cs @@ -3,6 +3,7 @@ using System.Diagnostics.Metrics; using BenchmarkDotNet.Attributes; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using Relayer.Serialization; namespace Relayer.Benchmarks; @@ -14,6 +15,8 @@ public class TelemetryBenchmarks private ServiceProvider _provider = null!; private ConsumePipeline _baseline = null!; private ConsumePipeline _instrumented = null!; + private ReceivePipeline _receive = null!; + private Incoming _incoming = null!; private MeterListener? _listener; private EndpointTelemetry _endpoint = null!; private ConsumeMessage _message; @@ -21,11 +24,15 @@ public class TelemetryBenchmarks [Params(false, true)] public bool ListenerAttached { get; set; } + [Params(false, true)] + public bool ErrorLoggingEnabled { get; set; } + [GlobalSetup] public void Setup() { var services = new ServiceCollection(); services.AddSingleton(); + services.AddSingleton(new LoggerFactory(ErrorLoggingEnabled)); services.AddRelayer(r => { r.MessageTypes.Add("benchmark.payload"); r.Handler(); }); _provider = services.BuildServiceProvider(); var instrumentation = _provider.GetRequiredService(); @@ -49,6 +56,8 @@ public void Setup() } _baseline = Builder().Build(1); _instrumented = Builder().Telemetry(_endpoint).Build(1); + _receive = new(_instrumented, new HeaderNames(), 1); + _incoming = new(); _message = new() { MessageId = "benchmark", MessageType = new("benchmark.payload", 1), Body = default }; } @@ -70,6 +79,9 @@ public async ValueTask ConsumerWithTelemetry() await _instrumented.ProcessAsync(context).ConfigureAwait(false); } + [Benchmark] + public ValueTask NativeConsumerWithTelemetry() => _receive.ProcessAsync(_incoming); + [Benchmark] public void FailureMeasurement() => _endpoint.RecordDuration(TimeSpan.FromMilliseconds(1), failed: true); @@ -80,6 +92,39 @@ public void Cleanup() _provider.Dispose(); } + // No provider allocation or output: isolate pipeline scope work while Error logging is enabled. + private sealed class LoggerFactory(bool enabled) : ILoggerFactory, ILogger + { + public ILogger CreateLogger(string categoryName) => this; + public bool IsEnabled(LogLevel level) => enabled && level >= LogLevel.Error; + public IDisposable? BeginScope(TState state) where TState : notnull => null; + public void Log(LogLevel level, EventId id, TState state, Exception? error, Func formatter) { } + public void AddProvider(ILoggerProvider provider) => throw new NotSupportedException(); + public void Dispose() { } + } + private sealed class Incoming + { + internal byte[] Id { get; } = "benchmark"u8.ToArray(); + internal byte[] Type { get; } = "benchmark.payload;v=1"u8.ToArray(); + internal byte[] Correlation { get; } = "conversation"u8.ToArray(); + } + private readonly struct Binding : IMessageBinding + { + public static ReadOnlySequence GetBody(Incoming message) => default; + 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), + "ce_correlationid" => new(message.Correlation), + _ => default, + }; + return !value.IsEmpty; + } + } + public sealed class Payload; public sealed class Handler : IHandler { diff --git a/docs/telemetry.md b/docs/telemetry.md index c83a7742e..a44b58f19 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -41,6 +41,6 @@ Generated error logs use category `Relayer.ConsumePipeline` and event ID 1. When NativeHeaderWriter.SetHeader(nativeMessage, names.CorrelationId, correlationId); ``` -Scope state belongs to the pooled delivery context. Logging providers must snapshot scope values synchronously during logging before queuing an entry for asynchronous export. +Scope values are read and cached lazily when a logging provider accesses them. Successful deliveries do not format identities or read optional correlation headers merely because Error logging is enabled. Typed deliveries reuse the precomputed wire type string; native malformed fields remain available without envelope parsing. Providers that eagerly snapshot scopes can still incur decoding costs. Scope state belongs to the pooled delivery context. Logging providers must snapshot scope values synchronously during logging before queuing an entry for asynchronous export. Health integration is tracked separately in #85; tracing in #13. See [design §8](design.md#8-observability) for their contracts. diff --git a/src/Relayer/Pipeline/ConsumePipeline.cs b/src/Relayer/Pipeline/ConsumePipeline.cs index 087404118..577c2672e 100644 --- a/src/Relayer/Pipeline/ConsumePipeline.cs +++ b/src/Relayer/Pipeline/ConsumePipeline.cs @@ -104,6 +104,15 @@ internal MessageType ResolveWireIdentity(WireString wire) return new(unknown[..separator], version); } + internal string GetWireIdentityText(MessageType messageType) + { + foreach (var identity in _wireIdentities) + { + if (identity.Identity == messageType) return identity.Text; + } + return messageType.ToString(); + } + private readonly record struct WireIdentity(MessageType Identity, string Text, byte[] Utf8); /// Processes one delivery in a fresh async DI scope, then invokes the configured native settlement callback. diff --git a/src/Relayer/Pipeline/DefaultMessageContext.cs b/src/Relayer/Pipeline/DefaultMessageContext.cs index ec8c61c3f..6b49e762b 100644 --- a/src/Relayer/Pipeline/DefaultMessageContext.cs +++ b/src/Relayer/Pipeline/DefaultMessageContext.cs @@ -45,17 +45,17 @@ internal void InitializeAttempts() internal ConsumeLogScope LogScope { get; } = new(); internal HeaderNames EnvelopeNames => _receive?.EnvelopeNames ?? _owner.EnvelopeNames; - internal void GetLogIdentity(out string? id, out string? type) + // Read raw native fields so malformed envelopes remain loggable without parsing required fields. + internal string? GetLogMessageId() { - if (_receive is null) - { - id = _message.MessageId; - type = _message.MessageType.ToString(); - return; - } - // Logging must also work for malformed envelopes without trying to parse their required fields. - id = _receive.TryGetValue(EnvelopeNames.Id, out var rawId) ? rawId.ToString() : null; - type = _receive.TryGetValue(EnvelopeNames.Type, out var rawType) ? rawType.ToString() : null; + if (_receive is null) return _message.MessageId; + return _receive.TryGetValue(EnvelopeNames.Id, out var id) ? id.ToString() : null; + } + + internal string? GetLogMessageType() + { + if (_receive is null) return _owner.GetWireIdentityText(_message.MessageType); + return _receive.TryGetValue(EnvelopeNames.Type, out var type) ? type.ToString() : null; } internal void Initialize(in ConsumeMessage message, CancellationToken cancellationToken) diff --git a/src/Relayer/Telemetry/ConsumeLog.cs b/src/Relayer/Telemetry/ConsumeLog.cs index 498e1cefb..63ffe1a35 100644 --- a/src/Relayer/Telemetry/ConsumeLog.cs +++ b/src/Relayer/Telemetry/ConsumeLog.cs @@ -12,29 +12,34 @@ internal static partial class ConsumeLog // Each pooled context owns its scope state; it is never shared across concurrent deliveries. internal sealed class ConsumeLogScope : IReadOnlyList> { + private DefaultMessageContext? _context; private string? _id; private string? _type; private string? _correlation; public int Count => 3; public KeyValuePair this[int index] => index switch { - 0 => new("MessageId", _id), - 1 => new("MessageType", _type), - 2 => new("CorrelationId", _correlation), + 0 => new("MessageId", _id ??= _context?.GetLogMessageId()), + 1 => new("MessageType", _type ??= _context?.GetLogMessageType()), + 2 => new("CorrelationId", _correlation ??= GetCorrelationId()), _ => throw new ArgumentOutOfRangeException(nameof(index)), }; - internal void Initialize(DefaultMessageContext context) + internal void Initialize(DefaultMessageContext context) => _context = context; + + private string? GetCorrelationId() => + _context is { } context && context.Headers.TryGetValue(context.EnvelopeNames.CorrelationId, out var value) + ? value.ToString() : null; + + internal void Clear() { - context.GetLogIdentity(out _id, out _type); - _correlation = context.Headers.TryGetValue(context.EnvelopeNames.CorrelationId, out var value) ? value.ToString() : null; + _context = null; + (_id, _type, _correlation) = (null, null, null); } - - internal void Clear() => (_id, _type, _correlation) = (null, null, null); public IEnumerator> GetEnumerator() { for (var i = 0; i < Count; i++) yield return this[i]; } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); - public override string ToString() => $"MessageId={_id} MessageType={_type} CorrelationId={_correlation}"; + public override string ToString() => $"MessageId={this[0].Value} MessageType={this[1].Value} CorrelationId={this[2].Value}"; } diff --git a/tests/Relayer.Tests/TelemetryTests.cs b/tests/Relayer.Tests/TelemetryTests.cs index 350771be7..68e33d41a 100644 --- a/tests/Relayer.Tests/TelemetryTests.cs +++ b/tests/Relayer.Tests/TelemetryTests.cs @@ -163,6 +163,27 @@ public async Task Correlation_scope_reads_the_native_binding_and_clears_on_reuse var receive = new ReceivePipeline(pipeline, new HeaderNames(prefix), 1); await receive.ProcessAsync(new Incoming { Prefix = prefix, CorrelationId = "conversation", Utf8 = utf8 }); await receive.ProcessAsync(new Incoming { Prefix = prefix, Utf8 = utf8 }); + await Assert.That(logger.Entries[0].Scope["MessageId"]).IsEqualTo("native"); + await Assert.That(logger.Entries[0].Scope["MessageType"]).IsEqualTo("number;v=1"); + await Assert.That(logger.Entries[0].Scope["CorrelationId"]).IsEqualTo("conversation"); + await Assert.That(logger.Entries[1].Scope["CorrelationId"]).IsNull(); + } + + [Test] + public async Task Typed_log_scopes_reuse_registered_wire_type_and_clear_cached_values() + { + var logger = new Logger(); + using var instrumentation = new RelayerInstrumentation(new LoggerFactory(logger)); + await using var provider = Provider(); + provider.GetRequiredService().Handle = _ => ValueTask.FromException(new Exception("handler")); + var pipeline = Builder(provider).Telemetry(instrumentation.CreateEndpoint(Options())).Build(1); + using (var context = pipeline.RentContext(Message() with { Headers = new Headers() })) + await pipeline.ProcessAsync(context); + using (var context = pipeline.RentContext(Message() with { MessageId = "next" })) + await pipeline.ProcessAsync(context); + await Assert.That(logger.Entries[0].Scope["MessageType"]).IsSameReferenceAs(logger.Entries[1].Scope["MessageType"]); + await Assert.That(logger.Entries[0].Scope["MessageId"]).IsEqualTo("delivery"); + await Assert.That(logger.Entries[1].Scope["MessageId"]).IsEqualTo("next"); await Assert.That(logger.Entries[0].Scope["CorrelationId"]).IsEqualTo("conversation"); await Assert.That(logger.Entries[1].Scope["CorrelationId"]).IsNull(); } @@ -223,6 +244,38 @@ public async Task Disabled_listeners_and_logging_do_not_read_optional_headers_an } } + [Test] + public async Task Error_logging_leaves_scope_values_unread_until_a_log_is_emitted() + { + var logger = new Logger(); + using var instrumentation = new RelayerInstrumentation(new LoggerFactory(logger)); + await using var provider = Provider(); + var pipeline = Builder(provider).Telemetry(instrumentation.CreateEndpoint(Options())).Build(1); + for (var i = 0; i < 2; i++) + { + using var context = pipeline.RentContext(Message() with { Headers = new UnreadHeaders() }); + await pipeline.ProcessAsync(context); + await Assert.That(context.LogScope[0].Value).IsNull(); + } + await Assert.That(logger.Entries.Count).IsEqualTo(0); + await Assert.That(logger.CurrentScope).IsNull(); + } + + [Test] + public async Task Error_logging_leaves_native_optional_headers_unread_on_success() + { + var logger = new Logger(); + using var instrumentation = new RelayerInstrumentation(new LoggerFactory(logger)); + await using var provider = Provider(); + var pipeline = Builder(provider).Telemetry(instrumentation.CreateEndpoint(Options())).Build(1); + var receive = new ReceivePipeline(pipeline, new HeaderNames("cloudEvents:"), 1); + var message = new Incoming { Utf8 = true, CorrelationId = "conversation" }; + await receive.ProcessAsync(message); + await receive.ProcessAsync(message); + await Assert.That(message.OptionalReads).IsEqualTo(0); + await Assert.That(logger.Entries.Count).IsEqualTo(0); + } + [Test] public async Task Malformed_envelopes_still_log_and_count_delivery_without_logging_bypassing_failure_handling() { @@ -237,6 +290,8 @@ public async Task Malformed_envelopes_still_log_and_count_delivery_without_loggi await receive.ProcessAsync(new Incoming { Type = null }); await Assert.That(failures).IsEqualTo(1); await Assert.That(logger.Entries.Single().Exception is MessageEnvelopeException).IsTrue(); + await Assert.That(logger.Entries.Single().Scope["MessageId"]).IsEqualTo("native"); + await Assert.That(logger.Entries.Single().Scope["MessageType"]).IsNull(); await Assert.That(capture.Values.Count(v => v.Name == "messaging.client.consumed.messages")).IsEqualTo(1); } @@ -401,6 +456,7 @@ private sealed class Incoming public string Prefix { get; init; } = "cloudEvents:"; public string? CorrelationId { get; init; } public bool Utf8 { get; init; } + public int OptionalReads { get; set; } public string Time { get; } = DateTimeOffset.UtcNow.AddMinutes(-1).ToString("O"); } private readonly struct Binding : IMessageBinding @@ -412,8 +468,8 @@ public static bool TryGetHeader(Incoming message, string name, out WireString va string? text = null; if (name == message.Prefix + "type") text = message.Type; else if (name == message.Prefix + "id") text = "native"; - else if (name == message.Prefix + "time") text = message.Time; - else if (name == message.Prefix + "correlationid") text = message.CorrelationId; + else if (name == message.Prefix + "time") { message.OptionalReads++; text = message.Time; } + else if (name == message.Prefix + "correlationid") { message.OptionalReads++; text = message.CorrelationId; } value = default; if (text is not null) value = message.Utf8 ? new(System.Text.Encoding.UTF8.GetBytes(text)) : new(text); From 869d50241c9f643a32a942cbe65ceeae2ea93b5a Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:17:34 +0000 Subject: [PATCH 5/8] fix: open consume log scopes only for failures (#84) --- Directory.Packages.props | 1 + .../Relayer.Benchmarks.csproj | 1 + .../Relayer.Benchmarks/TelemetryBenchmarks.cs | 14 ++- docs/decisions.md | 1 + docs/design.md | 2 +- docs/telemetry.md | 4 +- src/Relayer/Pipeline/ConsumePipeline.cs | 20 +--- src/Relayer/Pipeline/DefaultMessageContext.cs | 1 - src/Relayer/Telemetry/ConsumeLog.cs | 43 ++----- tests/Relayer.Tests/Relayer.Tests.csproj | 1 + tests/Relayer.Tests/TelemetryTests.cs | 109 +++++++++++++++++- 11 files changed, 137 insertions(+), 60 deletions(-) diff --git a/Directory.Packages.props b/Directory.Packages.props index 5d97dcd9b..651cabf01 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -35,6 +35,7 @@ + diff --git a/benchmarks/Relayer.Benchmarks/Relayer.Benchmarks.csproj b/benchmarks/Relayer.Benchmarks/Relayer.Benchmarks.csproj index 95d163520..eb9d5c81c 100644 --- a/benchmarks/Relayer.Benchmarks/Relayer.Benchmarks.csproj +++ b/benchmarks/Relayer.Benchmarks/Relayer.Benchmarks.csproj @@ -9,6 +9,7 @@ + diff --git a/benchmarks/Relayer.Benchmarks/TelemetryBenchmarks.cs b/benchmarks/Relayer.Benchmarks/TelemetryBenchmarks.cs index daf123333..c72e02c1e 100644 --- a/benchmarks/Relayer.Benchmarks/TelemetryBenchmarks.cs +++ b/benchmarks/Relayer.Benchmarks/TelemetryBenchmarks.cs @@ -32,7 +32,9 @@ public void Setup() { var services = new ServiceCollection(); services.AddSingleton(); - services.AddSingleton(new LoggerFactory(ErrorLoggingEnabled)); + services.AddLogging(logging => logging + .SetMinimumLevel(ErrorLoggingEnabled ? LogLevel.Error : LogLevel.None) + .AddProvider(new ScopeProvider())); services.AddRelayer(r => { r.MessageTypes.Add("benchmark.payload"); r.Handler(); }); _provider = services.BuildServiceProvider(); var instrumentation = _provider.GetRequiredService(); @@ -92,14 +94,14 @@ public void Cleanup() _provider.Dispose(); } - // No provider allocation or output: isolate pipeline scope work while Error logging is enabled. - private sealed class LoggerFactory(bool enabled) : ILoggerFactory, ILogger + // LoggerFactory supplies real external scopes; output is disabled to isolate pipeline overhead. + private sealed class ScopeProvider : ILoggerProvider, ISupportExternalScope, ILogger { public ILogger CreateLogger(string categoryName) => this; - public bool IsEnabled(LogLevel level) => enabled && level >= LogLevel.Error; - public IDisposable? BeginScope(TState state) where TState : notnull => null; + public bool IsEnabled(LogLevel level) => level >= LogLevel.Error; + public void SetScopeProvider(IExternalScopeProvider scopeProvider) { } + public IDisposable? BeginScope(TState state) where TState : notnull => throw new NotSupportedException(); public void Log(LogLevel level, EventId id, TState state, Exception? error, Func formatter) { } - public void AddProvider(ILoggerProvider provider) => throw new NotSupportedException(); public void Dispose() { } } private sealed class Incoming diff --git a/docs/decisions.md b/docs/decisions.md index dab4481f3..c5e365c69 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -211,6 +211,7 @@ Superseded by [D24](#d24-capabilities-are-valued-and-declared-per-endpoint). - W3C trace context is propagated in native headers. - The outbox captures trace context at enqueue time. - Processing duration is measured after settlement. +- Generated failure logs open an identity scope only around the log call. `LoggerFactory` allocates when it pushes an external scope, so successful deliveries must not open a Relayer scope. Failure scopes contain read-only snapshots rather than pooled context references, allowing providers to retain them for asynchronous export. - Enrichers are supported. ## D16. Topology is declared; default mode is Validate diff --git a/docs/design.md b/docs/design.md index c04d34e9b..68a1b9586 100644 --- a/docs/design.md +++ b/docs/design.md @@ -637,7 +637,7 @@ Relayer-specific instruments, for which the conventions define nothing: ### 8.6 Logging and health -- Logging uses `LoggerMessage` source generation (zero allocations when disabled) and scopes that carry the message ID, type, and correlation ID. +- Logging uses `LoggerMessage` source generation and scopes that carry the message ID, type, and correlation ID around generated failure logs. Successful deliveries open no logging scope, preserving zero incremental allocations with Error logging enabled. Failure scopes hold read-only identity snapshots that providers can retain after processing. - Health checks: transport connectivity, consumer liveness (each consumer has made progress or is idle), and outbox backlog thresholds. --- diff --git a/docs/telemetry.md b/docs/telemetry.md index a44b58f19..d9f997af2 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -35,12 +35,12 @@ Each recorder retains precomputed `TagList` values, including its failure tags. The consumer reads the transport binding's CloudEvents time header only when `relayer.critical_time` has a listener. Invalid or missing timestamps produce no critical-time measurement. With logging and metrics disabled, optional headers remain unread and telemetry adds no per-delivery allocations. -Generated error logs use category `Relayer.ConsumePipeline` and event ID 1. When Error logging is enabled for that category, the delivery scope carries `MessageId`, the stable wire `MessageType`, and `CorrelationId` from the optional CloudEvents `correlationid` extension (`ce_correlationid` or `cloudEvents:correlationid`, resolved through `HeaderNames.CorrelationId`). The scope covers handling, failure handling, disposal and settlement. Cancellation with the delivery token canceled propagates without an Error log, while unrelated cancellation failures are logged normally. Failures log the exception and the ambient activity's `TraceId` and `SpanId`; no activity is created by this metrics/logging integration. Raw malformed envelope fields remain loggable without bypassing the failure classifier. Producers opt into correlation by writing the extension through their native header writer using `names.CorrelationId`; the envelope writer does not invent a correlation ID. Native adapters expose that header through their lazy binding, including messages from non-Relayer producers. For example, after writing the envelope: +Generated error logs use category `Relayer.ConsumePipeline` and event ID 1. When Error logging is enabled for that category, each generated failure log opens a scope carrying `MessageId`, the stable wire `MessageType`, and `CorrelationId` from the optional CloudEvents `correlationid` extension (`ce_correlationid` or `cloudEvents:correlationid`, resolved through `HeaderNames.CorrelationId`). Failures in handling, failure handling, disposal and settlement receive this scope. It surrounds only the generated log call; application and failure-handler logs retain the application's ambient scopes. Successful deliveries open no Relayer logging scope, because `LoggerFactory` allocates when pushing an external scope. Cancellation with the delivery token canceled propagates without an Error log, while unrelated cancellation failures are logged normally. Failures log the exception and the ambient activity's `TraceId` and `SpanId`; no activity is created by this metrics/logging integration. Raw malformed envelope fields remain loggable without bypassing the failure classifier. Producers opt into correlation by writing the extension through their native header writer using `names.CorrelationId`; the envelope writer does not invent a correlation ID. Native adapters expose that header through their lazy binding, including messages from non-Relayer producers. For example, after writing the envelope: ```csharp NativeHeaderWriter.SetHeader(nativeMessage, names.CorrelationId, correlationId); ``` -Scope values are read and cached lazily when a logging provider accesses them. Successful deliveries do not format identities or read optional correlation headers merely because Error logging is enabled. Typed deliveries reuse the precomputed wire type string; native malformed fields remain available without envelope parsing. Providers that eagerly snapshot scopes can still incur decoding costs. Scope state belongs to the pooled delivery context. Logging providers must snapshot scope values synchronously during logging before queuing an entry for asynchronous export. +Scope identities are captured in a read-only snapshot only when a generated failure log is emitted. Successful deliveries do not format identities or read optional correlation headers merely because Error logging is enabled. Typed deliveries reuse the precomputed wire type string; native malformed fields remain available without envelope parsing. A provider can retain the scope snapshot for asynchronous export after the context is cleared or reused. Snapshot, scope-push and enumeration allocations occur only on the failure path. Health integration is tracked separately in #85; tracing in #13. See [design §8](design.md#8-observability) for their contracts. diff --git a/src/Relayer/Pipeline/ConsumePipeline.cs b/src/Relayer/Pipeline/ConsumePipeline.cs index 577c2672e..3b534e3f9 100644 --- a/src/Relayer/Pipeline/ConsumePipeline.cs +++ b/src/Relayer/Pipeline/ConsumePipeline.cs @@ -130,15 +130,9 @@ private async ValueTask ProcessCoreAsync(DefaultMessageContext context) var telemetry = _telemetry; var start = telemetry is { DurationEnabled: true } ? Stopwatch.GetTimestamp() : 0; Exception? failure = null; - IDisposable? logScope = null; try { telemetry?.RecordConsumed(); - if (telemetry?.Logger.IsEnabled(LogLevel.Error) == true) - { - context.LogScope.Initialize(context); - logScope = telemetry.Logger.BeginScope(context.LogScope); - } context.CancellationToken.ThrowIfCancellationRequested(); var scope = new AsyncServiceScope(_scopes.CreateScope()); try @@ -155,7 +149,7 @@ private async ValueTask ProcessCoreAsync(DefaultMessageContext context) catch (Exception error) { failure = error; - LogFailure(telemetry, error); + LogFailure(telemetry, context, error); await _failure(context, error, _classifier.Classify(error, context)).ConfigureAwait(false); } } @@ -170,7 +164,7 @@ private async ValueTask ProcessCoreAsync(DefaultMessageContext context) catch (OperationCanceledException) when (context.CancellationToken.IsCancellationRequested) { throw; } catch (Exception error) { - if (!ReferenceEquals(failure, error)) LogFailure(telemetry, error); + if (!ReferenceEquals(failure, error)) LogFailure(telemetry, context, error); failure = error; throw; } @@ -183,12 +177,7 @@ private async ValueTask ProcessCoreAsync(DefaultMessageContext context) } finally { - try { logScope?.Dispose(); } - finally - { - context.LogScope.Clear(); - context.EndProcessing(); - } + context.EndProcessing(); } } } @@ -275,9 +264,10 @@ private async ValueTask ProcessWithFailuresAsync(DefaultMessageContext context) } } - private static void LogFailure(EndpointTelemetry? telemetry, Exception error) + private static void LogFailure(EndpointTelemetry? telemetry, DefaultMessageContext context, Exception error) { if (telemetry?.Logger.IsEnabled(LogLevel.Error) != true) return; + using var scope = telemetry.Logger.BeginScope(ConsumeLog.CreateScope(context)); var activity = Activity.Current; ConsumeLog.Failed(telemetry.Logger, error, activity?.TraceId.ToString(), activity?.SpanId.ToString()); } diff --git a/src/Relayer/Pipeline/DefaultMessageContext.cs b/src/Relayer/Pipeline/DefaultMessageContext.cs index 6b49e762b..701f6acef 100644 --- a/src/Relayer/Pipeline/DefaultMessageContext.cs +++ b/src/Relayer/Pipeline/DefaultMessageContext.cs @@ -42,7 +42,6 @@ internal void InitializeAttempts() } internal void NextAttempt() => _attempt = checked(Attempt + 1); internal ConsumeDelegate Dispatch { get; set; } = null!; - internal ConsumeLogScope LogScope { get; } = new(); internal HeaderNames EnvelopeNames => _receive?.EnvelopeNames ?? _owner.EnvelopeNames; // Read raw native fields so malformed envelopes remain loggable without parsing required fields. diff --git a/src/Relayer/Telemetry/ConsumeLog.cs b/src/Relayer/Telemetry/ConsumeLog.cs index 63ffe1a35..9dd8408d0 100644 --- a/src/Relayer/Telemetry/ConsumeLog.cs +++ b/src/Relayer/Telemetry/ConsumeLog.cs @@ -1,4 +1,4 @@ -using System.Collections; +using System.Collections.ObjectModel; using Microsoft.Extensions.Logging; namespace Relayer; @@ -7,39 +7,20 @@ internal static partial class ConsumeLog { [LoggerMessage(1, LogLevel.Error, "Message processing failed. TraceId={TraceId} SpanId={SpanId}.")] internal static partial void Failed(ILogger logger, Exception exception, string? traceId, string? spanId); -} -// Each pooled context owns its scope state; it is never shared across concurrent deliveries. -internal sealed class ConsumeLogScope : IReadOnlyList> -{ - private DefaultMessageContext? _context; - private string? _id; - private string? _type; - private string? _correlation; - public int Count => 3; - public KeyValuePair this[int index] => index switch + // Snapshot only for an emitted failure. Providers can retain it after the context returns to its pool. + internal static IReadOnlyList> CreateScope(DefaultMessageContext context) { - 0 => new("MessageId", _id ??= _context?.GetLogMessageId()), - 1 => new("MessageType", _type ??= _context?.GetLogMessageType()), - 2 => new("CorrelationId", _correlation ??= GetCorrelationId()), - _ => throw new ArgumentOutOfRangeException(nameof(index)), - }; - - internal void Initialize(DefaultMessageContext context) => _context = context; - - private string? GetCorrelationId() => - _context is { } context && context.Headers.TryGetValue(context.EnvelopeNames.CorrelationId, out var value) + var correlation = context.Headers.TryGetValue(context.EnvelopeNames.CorrelationId, out var value) ? value.ToString() : null; - - internal void Clear() - { - _context = null; - (_id, _type, _correlation) = (null, null, null); + return new ConsumeLogScope(context.GetLogMessageId(), context.GetLogMessageType(), correlation); } - public IEnumerator> GetEnumerator() - { - for (var i = 0; i < Count; i++) yield return this[i]; - } - IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); +} + +internal sealed class ConsumeLogScope(string? messageId, string? messageType, string? correlationId) + : ReadOnlyCollection>([ + new("MessageId", messageId), new("MessageType", messageType), new("CorrelationId", correlationId), + ]) +{ public override string ToString() => $"MessageId={this[0].Value} MessageType={this[1].Value} CorrelationId={this[2].Value}"; } diff --git a/tests/Relayer.Tests/Relayer.Tests.csproj b/tests/Relayer.Tests/Relayer.Tests.csproj index c8bdab110..8030c68ba 100644 --- a/tests/Relayer.Tests/Relayer.Tests.csproj +++ b/tests/Relayer.Tests/Relayer.Tests.csproj @@ -9,6 +9,7 @@ + diff --git a/tests/Relayer.Tests/TelemetryTests.cs b/tests/Relayer.Tests/TelemetryTests.cs index 68e33d41a..ddddb74b9 100644 --- a/tests/Relayer.Tests/TelemetryTests.cs +++ b/tests/Relayer.Tests/TelemetryTests.cs @@ -170,7 +170,7 @@ public async Task Correlation_scope_reads_the_native_binding_and_clears_on_reuse } [Test] - public async Task Typed_log_scopes_reuse_registered_wire_type_and_clear_cached_values() + public async Task Typed_log_scopes_reuse_registered_wire_type_and_snapshot_each_failure() { var logger = new Logger(); using var instrumentation = new RelayerInstrumentation(new LoggerFactory(logger)); @@ -231,7 +231,7 @@ public async Task Settlement_is_skipped_after_failed_durability_and_settlement_e } [Test] - public async Task Disabled_listeners_and_logging_do_not_read_optional_headers_and_context_reuse_clears_scope() + public async Task Disabled_listeners_and_logging_do_not_read_optional_headers() { await using var provider = Provider(); var instrumentation = provider.GetRequiredService(); @@ -240,7 +240,6 @@ public async Task Disabled_listeners_and_logging_do_not_read_optional_headers_an { using var context = pipeline.RentContext(Message() with { Headers = new UnreadHeaders() }); await pipeline.ProcessAsync(context); - await Assert.That(context.LogScope[0].Value).IsNull(); } } @@ -255,10 +254,10 @@ public async Task Error_logging_leaves_scope_values_unread_until_a_log_is_emitte { using var context = pipeline.RentContext(Message() with { Headers = new UnreadHeaders() }); await pipeline.ProcessAsync(context); - await Assert.That(context.LogScope[0].Value).IsNull(); } await Assert.That(logger.Entries.Count).IsEqualTo(0); await Assert.That(logger.CurrentScope).IsNull(); + await Assert.That(logger.ScopesStarted).IsEqualTo(0); } [Test] @@ -274,6 +273,87 @@ public async Task Error_logging_leaves_native_optional_headers_unread_on_success await receive.ProcessAsync(message); await Assert.That(message.OptionalReads).IsEqualTo(0); await Assert.That(logger.Entries.Count).IsEqualTo(0); + await Assert.That(logger.ScopesStarted).IsEqualTo(0); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Successful_delivery_adds_no_scope_to_real_logger_factory(bool native) + { + var logs = new ExternalScopeProvider(); + using var factory = Microsoft.Extensions.Logging.LoggerFactory.Create(logging => logging.AddProvider(logs)); + using var instrumentation = new RelayerInstrumentation(factory); + await using var provider = Provider(); + var observed = new List(); + provider.GetRequiredService().Handle = _ => + { + logs.Scopes.ForEachScope(static (scope, scopes) => scopes.Add(scope!), observed); + return default; + }; + var pipeline = Builder(provider).Telemetry(instrumentation.CreateEndpoint(Options())).Build(1); + using var parent = factory.CreateLogger("application").BeginScope("application scope"); + if (native) + await new ReceivePipeline(pipeline, new HeaderNames("cloudEvents:"), 1) + .ProcessAsync(new Incoming { Utf8 = true }); + else + { + using var context = pipeline.RentContext(Message() with { Headers = new UnreadHeaders() }); + await pipeline.ProcessAsync(context); + } + await Assert.That(observed.Count).IsEqualTo(1); + await Assert.That(observed[0]).IsEqualTo("application scope"); + } + + [Test] + [Arguments("handler")] + [Arguments("failure")] + [Arguments("disposal")] + [Arguments("settlement")] + public async Task Generated_failure_scopes_survive_context_reuse_and_restore_application_scope(string stage) + { + var logs = new ExternalScopeProvider(); + using var factory = Microsoft.Extensions.Logging.LoggerFactory.Create(logging => logging.AddProvider(logs)); + using var instrumentation = new RelayerInstrumentation(factory); + await using var provider = Provider(services => services.AddScoped()); + var error = new ApplicationException(stage); + provider.GetRequiredService().Handle = context => + { + if (stage == "disposal") context.Services.GetRequiredService(); + return stage is "handler" or "failure" ? ValueTask.FromException(error) : default; + }; + var pipeline = Builder(provider, (_, _, _) => stage == "failure" + ? ValueTask.FromException(new InvalidOperationException("failure handling")) : default) + .Telemetry(instrumentation.CreateEndpoint(Options())) + .Settle(_ => stage == "settlement" ? ValueTask.FromException(error) : default).Build(1); + using var parent = factory.CreateLogger("application").BeginScope("application scope"); + foreach (var id in new[] { "delivery", "next" }) + { + using var context = pipeline.RentContext(Message() with + { + MessageId = id, Headers = id == "delivery" ? new Headers() : null, + }); + if (stage == "handler") await pipeline.ProcessAsync(context); + else await Assert.That(async () => await pipeline.ProcessAsync(context)).Throws(); + } + + // Read retained states only after both pooled deliveries have returned. + var entriesPerDelivery = stage == "failure" ? 2 : 1; + await Assert.That(logs.RetainedScopes.Count).IsEqualTo(2 * entriesPerDelivery); + for (var i = 0; i < logs.RetainedScopes.Count; i++) + { + var snapshot = logs.RetainedScopes[i].ToDictionary(); + await Assert.That(snapshot["MessageId"]).IsEqualTo(i < entriesPerDelivery ? "delivery" : "next"); + await Assert.That(snapshot["MessageType"]).IsEqualTo("number;v=1"); + await Assert.That(snapshot["CorrelationId"]).IsEqualTo(i < entriesPerDelivery ? "conversation" : null); + await Assert.That(logs.RetainedScopes[i].ToString()).IsEqualTo(i < entriesPerDelivery + ? "MessageId=delivery MessageType=number;v=1 CorrelationId=conversation" + : "MessageId=next MessageType=number;v=1 CorrelationId="); + } + var remaining = new List(); + logs.Scopes.ForEachScope(static (scope, scopes) => scopes.Add(scope!), remaining); + await Assert.That(remaining.Count).IsEqualTo(1); + await Assert.That(remaining[0]).IsEqualTo("application scope"); } [Test] @@ -450,6 +530,10 @@ public ValueTask DisposeAsync() return new(Finished.Task); } } + private sealed class DisposalFailure : IAsyncDisposable + { + public ValueTask DisposeAsync() => ValueTask.FromException(new InvalidOperationException("disposal")); + } private sealed class Incoming { public string? Type { get; init; } = "number;v=1"; @@ -504,11 +588,13 @@ private void Add(Instrument instrument, double value, ReadOnlySpan Scope, Dictionary State); private sealed class Logger : ILogger { + internal int ScopesStarted { get; private set; } internal IReadOnlyList>? CurrentScope { get; private set; } internal List Entries { get; } = []; public bool IsEnabled(LogLevel logLevel) => true; public IDisposable? BeginScope(TState state) where TState : notnull { + ScopesStarted++; CurrentScope = (IReadOnlyList>)(object)state; return new Scope(this); } @@ -516,6 +602,21 @@ public void Log(LogLevel level, EventId id, TState state, Exception? err Entries.Add(new(error, CurrentScope!.ToDictionary(), ((IEnumerable>)(object)state!).ToDictionary())); private sealed class Scope(Logger owner) : IDisposable { public void Dispose() => owner.CurrentScope = null; } } + private sealed class ExternalScopeProvider : ILoggerProvider, ISupportExternalScope, ILogger + { + internal IExternalScopeProvider Scopes { get; private set; } = null!; + internal List>> RetainedScopes { get; } = []; + public void SetScopeProvider(IExternalScopeProvider scopeProvider) => Scopes = scopeProvider; + public ILogger CreateLogger(string categoryName) => this; + public bool IsEnabled(LogLevel level) => true; + public IDisposable? BeginScope(TState state) where TState : notnull => throw new NotSupportedException(); + public void Log(LogLevel level, EventId id, TState state, Exception? error, Func formatter) => + Scopes.ForEachScope(static (scope, retained) => + { + if (scope is IReadOnlyList> identity) retained.Add(identity); + }, RetainedScopes); + public void Dispose() { } + } private sealed class LoggerFactory(Logger logger) : ILoggerFactory { public ILogger CreateLogger(string categoryName) => logger; From 9a7f91bacbd91191868ff185cd91b6f00ff8ebec Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:29:30 +0000 Subject: [PATCH 6/8] fix: integrate consume telemetry with executable failure handling (#84) --- .../FailurePipelineBenchmarks.cs | 14 +++ docs/telemetry.md | 4 +- src/Relayer/Pipeline/ConsumePipeline.cs | 52 +++++++-- src/Relayer/Pipeline/DefaultMessageContext.cs | 4 + src/Relayer/Pipeline/ReceiveMessageState.cs | 1 + src/Relayer/Pipeline/ReceivePipeline.cs | 2 + tests/Relayer.Tests/TelemetryTests.cs | 103 +++++++++++++++++- 7 files changed, 165 insertions(+), 15 deletions(-) diff --git a/benchmarks/Relayer.Benchmarks/FailurePipelineBenchmarks.cs b/benchmarks/Relayer.Benchmarks/FailurePipelineBenchmarks.cs index 34dfa30db..aca3fe9d6 100644 --- a/benchmarks/Relayer.Benchmarks/FailurePipelineBenchmarks.cs +++ b/benchmarks/Relayer.Benchmarks/FailurePipelineBenchmarks.cs @@ -15,6 +15,7 @@ public class FailurePipelineBenchmarks private IServiceScopeFactory _scopes = null!; private ConsumePipeline _consumer = null!; private ConsumePipeline _failures = null!; + private ConsumePipeline _instrumentedFailures = null!; private HandlerDescriptor _descriptor = null!; private readonly DirectContext _direct = new(); private readonly Serializer _serializer = new(); @@ -44,6 +45,12 @@ public void Setup() static (_, error, _) => ValueTask.FromException(error)).Handler(_descriptor).Build(1); _failures = new ConsumePipelineBuilder(_scopes, _provider.GetRequiredService(), _serializer, policy).Handler(_descriptor).Build(1); + var telemetry = _provider.GetRequiredService().CreateEndpoint(new() + { + System = "relayer.inmemory", Destination = "source", + }); + _instrumentedFailures = new ConsumePipelineBuilder(_scopes, _provider.GetRequiredService(), _serializer, + policy).Handler(_descriptor).Telemetry(telemetry).Build(1); _message = new() { MessageId = "benchmark", MessageType = new("benchmark.failure", 1), Body = default }; } @@ -74,6 +81,13 @@ public async ValueTask ExecutableFailurePipeline() await _failures.ProcessAsync(context).ConfigureAwait(false); } + [Benchmark] + public async ValueTask ExecutableFailurePipelineWithTelemetry() + { + using var context = _instrumentedFailures.RentContext(_message); + await _instrumentedFailures.ProcessAsync(context).ConfigureAwait(false); + } + [GlobalCleanup] public async Task Cleanup() => await _provider.DisposeAsync(); diff --git a/docs/telemetry.md b/docs/telemetry.md index d9f997af2..48bac42da 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -27,6 +27,8 @@ var consumer = new ConsumePipelineBuilder( The settlement callback reads the transport's native feature and its disposition. It runs only after durable processing, failure handling and async scope disposal succeed. It must honor `SettledByHandler`, use the broker's native semantics, and record its native operation with a separate endpoint recorder (`OperationName = "complete"`, `"ack"`, `"commit"`, etc.). `context.Services` is unavailable after scope disposal. A settlement error propagates to the receive loop without re-entering failure handling. If settlement runs outside this callback, its duration cannot be included in the process metric. Amortized commits stay outside per-message processing, as design §8.2 requires. +Both consumer constructors support telemetry and settlement. With an executable `FailurePipeline`, the native feature receives the resolved failure disposition before the settlement callback runs. Immediate retries share one delivery count and duration, including all attempt scopes, send flushes, durable failure work and settlement. Any processing failure in those attempts retains `error.type`, even when a later retry succeeds. + The consumer records one `messaging.client.consumed.messages` measurement per delivery and a `messaging.process.duration` measurement after settlement. Processing failures, including ones durably handled by the failure pipeline, mark the duration with `error.type = "_OTHER"`. Actual exception objects are retained in logs. This bounded fallback avoids runtime type lookups and message-derived metric dimensions. Delivery-token cancellation still counts as a delivery and records duration, but does not add `error.type`. If handling already failed before settlement is canceled, the duration retains that earlier failure. Cancellation before receive adaptation starts is not a delivery. Other execution components use the same recorder methods: `RecordSent` counts messages attempted at the broker, including failed attempts, but never an outbox enqueue. `RecordDuration` selects the process histogram only for `OperationName = "process"`; other operations use the client-operation histogram. Durations and dispatch lag use seconds. Outbox dispatch, retry, inbox, circuit and transport implementations call the corresponding recorder only when the actual action occurs. The current core exposes those recording seams; it does not infer retries or dead-letter success from a classifier decision. `RecordConsumerLag` accepts the native client's lag calculation. Circuit values are 0 closed, 1 open and 2 half-open. @@ -41,6 +43,6 @@ Generated error logs use category `Relayer.ConsumePipeline` and event ID 1. When NativeHeaderWriter.SetHeader(nativeMessage, names.CorrelationId, correlationId); ``` -Scope identities are captured in a read-only snapshot only when a generated failure log is emitted. Successful deliveries do not format identities or read optional correlation headers merely because Error logging is enabled. Typed deliveries reuse the precomputed wire type string; native malformed fields remain available without envelope parsing. A provider can retain the scope snapshot for asynchronous export after the context is cleared or reused. Snapshot, scope-push and enumeration allocations occur only on the failure path. +Scope identities are captured in a read-only snapshot only when a generated failure log is emitted. Successful deliveries do not format identities or read optional correlation headers merely because Error logging is enabled. Typed deliveries reuse the precomputed wire type string; native malformed fields remain available without envelope parsing. A provider can retain the scope snapshot for asynchronous export after the context is cleared or reused. Snapshot, scope-push and enumeration allocations occur only on the failure path. Exceptions from logging providers are contained so they cannot replace the delivery error or bypass durable failure handling. Health integration is tracked separately in #85; tracing in #13. See [design §8](design.md#8-observability) for their contracts. diff --git a/src/Relayer/Pipeline/ConsumePipeline.cs b/src/Relayer/Pipeline/ConsumePipeline.cs index 3b534e3f9..bf7d9cea2 100644 --- a/src/Relayer/Pipeline/ConsumePipeline.cs +++ b/src/Relayer/Pipeline/ConsumePipeline.cs @@ -185,14 +185,18 @@ private async ValueTask ProcessCoreAsync(DefaultMessageContext context) [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder))] private async ValueTask ProcessWithFailuresAsync(DefaultMessageContext context) { + var telemetry = _telemetry; + var start = telemetry is { DurationEnabled: true } ? Stopwatch.GetTimestamp() : 0; + Exception? failure = null; try { + telemetry?.RecordConsumed(); var retry = 0; var initialize = true; while (true) { context.CancellationToken.ThrowIfCancellationRequested(); - Exception? failure = null; + Exception? attemptFailure = null; var action = FailureAction.Retry; var scope = new AsyncServiceScope(_scopes.CreateScope()); Sender? sender = null; @@ -220,7 +224,8 @@ private async ValueTask ProcessWithFailuresAsync(DefaultMessageContext context) catch (OperationCanceledException) when (context.CancellationToken.IsCancellationRequested) { throw; } catch (Exception error) { - failure = error; + failure = attemptFailure = error; + LogFailure(telemetry, context, error); action = _classifier.Classify(error, context); _failures!.Record(context, error); } @@ -239,12 +244,12 @@ private async ValueTask ProcessWithFailuresAsync(DefaultMessageContext context) } } context.CancellationToken.ThrowIfCancellationRequested(); - if (failure is null) + if (attemptFailure is null) { // Dispose the successful scope before allowing sends to escape. A flush failure propagates: // some sends may have succeeded, so do not retry the handler or return a settlement decision. await context.SendBuffer.FlushAsync(context.CancellationToken).ConfigureAwait(false); - return; + break; } context.SendBuffer.Clear(); if (action == FailureAction.Retry && _failures!.CanRetry(retry)) @@ -253,23 +258,48 @@ private async ValueTask ProcessWithFailuresAsync(DefaultMessageContext context) context.NextAttempt(); continue; } - await _failures!.HandleAsync(context, failure, action).ConfigureAwait(false); - return; + await _failures!.HandleAsync(context, attemptFailure, action).ConfigureAwait(false); + context.ApplyFailureDisposition(); + break; } + context.ClearServices(); + if (_settlement is { } settle) await settle(context).ConfigureAwait(false); + } + catch (OperationCanceledException) when (context.CancellationToken.IsCancellationRequested) { throw; } + catch (Exception error) + { + if (!ReferenceEquals(failure, error)) LogFailure(telemetry, context, error); + failure = error; + throw; } finally { context.SendBuffer.Clear(); - context.EndProcessing(); + try + { + if (start != 0) telemetry!.RecordDuration(Stopwatch.GetElapsedTime(start), failure is not null); + telemetry?.RecordCriticalTime(context); + } + finally + { + context.EndProcessing(); + } } } private static void LogFailure(EndpointTelemetry? telemetry, DefaultMessageContext context, Exception error) { - if (telemetry?.Logger.IsEnabled(LogLevel.Error) != true) return; - using var scope = telemetry.Logger.BeginScope(ConsumeLog.CreateScope(context)); - var activity = Activity.Current; - ConsumeLog.Failed(telemetry.Logger, error, activity?.TraceId.ToString(), activity?.SpanId.ToString()); + try + { + if (telemetry?.Logger.IsEnabled(LogLevel.Error) != true) return; + using var scope = telemetry.Logger.BeginScope(ConsumeLog.CreateScope(context)); + var activity = Activity.Current; + ConsumeLog.Failed(telemetry.Logger, error, activity?.TraceId.ToString(), activity?.SpanId.ToString()); + } + catch (Exception) + { + // A broken logging provider must not replace the delivery error or skip durable failure handling. + } } private static ValueTask InvokeHandlerAsync(MessageContext context) => ((DefaultMessageContext)context).Dispatch(context); diff --git a/src/Relayer/Pipeline/DefaultMessageContext.cs b/src/Relayer/Pipeline/DefaultMessageContext.cs index 701f6acef..3b26e8216 100644 --- a/src/Relayer/Pipeline/DefaultMessageContext.cs +++ b/src/Relayer/Pipeline/DefaultMessageContext.cs @@ -34,6 +34,10 @@ public sealed class DefaultMessageContext : MessageContext, IDisposable internal int Redeliveries { get; private set; } internal FailureHistory? FailureHistory { get; set; } internal Disposition? FailureDisposition { get; set; } + internal void ApplyFailureDisposition() + { + if (FailureDisposition is { } disposition) _receive?.SetDisposition(disposition); + } internal AttemptSendBuffer SendBuffer { get; } = new(); internal void InitializeAttempts() { diff --git a/src/Relayer/Pipeline/ReceiveMessageState.cs b/src/Relayer/Pipeline/ReceiveMessageState.cs index 8718d0b96..1e9083776 100644 --- a/src/Relayer/Pipeline/ReceiveMessageState.cs +++ b/src/Relayer/Pipeline/ReceiveMessageState.cs @@ -5,6 +5,7 @@ namespace Relayer; internal abstract class ReceiveMessageState : MessageHeaders { internal abstract HeaderNames EnvelopeNames { get; } + internal abstract void SetDisposition(Disposition disposition); internal abstract string MessageId { get; } internal abstract MessageType MessageType { get; } internal abstract int Attempt { get; } diff --git a/src/Relayer/Pipeline/ReceivePipeline.cs b/src/Relayer/Pipeline/ReceivePipeline.cs index 9c11bdd8c..2bb509641 100644 --- a/src/Relayer/Pipeline/ReceivePipeline.cs +++ b/src/Relayer/Pipeline/ReceivePipeline.cs @@ -95,6 +95,8 @@ private sealed class State(ConsumePipeline consumer, HeaderNames names) : Receiv private ReadOnlySequence _body; internal NativeMessage Native { get; } = new(); + internal override void SetDisposition(Disposition disposition) => Native.Disposition = disposition; + internal void Initialize(TIncoming message) { Native.Message = message; diff --git a/tests/Relayer.Tests/TelemetryTests.cs b/tests/Relayer.Tests/TelemetryTests.cs index ddddb74b9..24ff68de0 100644 --- a/tests/Relayer.Tests/TelemetryTests.cs +++ b/tests/Relayer.Tests/TelemetryTests.cs @@ -5,12 +5,86 @@ using System.Diagnostics.Metrics; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Relayer.Transports; using Relayer.Serialization; namespace Relayer.Tests; public class TelemetryTests { + [Test] + [Arguments("enabled")] + [Arguments("scope")] + [Arguments("log")] + [Arguments("dispose")] + public async Task Throwing_logger_does_not_skip_durable_failure_handling(string stage) + { + var logger = new Logger { ThrowAt = stage }; + using var instrumentation = new RelayerInstrumentation(new LoggerFactory(logger)); + await using var provider = Provider(); + provider.GetRequiredService().Handle = static _ => throw new InvalidOperationException("handler"); + var failures = 0; + var settlements = 0; + var pipeline = Builder(provider, (_, error, _) => + { + if (error.Message != "handler") throw new InvalidOperationException("Original failure lost."); + failures++; + return default; + }).Telemetry(instrumentation.CreateEndpoint(Options())).Settle(_ => { settlements++; return default; }).Build(1); + using var context = pipeline.RentContext(Message()); + await pipeline.ProcessAsync(context); + await Assert.That(failures).IsEqualTo(1); + await Assert.That(settlements).IsEqualTo(1); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Executable_failure_pipeline_records_delivery_and_settles_after_durability(bool recover) + { + var logger = new Logger(); + using var instrumentation = new RelayerInstrumentation(new LoggerFactory(logger)); + using var capture = new Capture(instrumentation); + await using var provider = Provider(services => { services.AddSingleton(); services.AddSingleton(); }); + var attempts = 0; + provider.GetRequiredService().Handle = _ => + { + attempts++; + if (!recover || attempts == 1) throw new InvalidOperationException("handler"); + return default; + }; + var failures = new FailurePipeline(provider, "test", "orders", "billing", + new() { RetryDelays = new[] { TimeSpan.Zero }, Jitter = 0 }); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var finished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var consumer = new ConsumePipelineBuilder(provider.GetRequiredService(), + provider.GetRequiredService(), new Serializer(), failures) + .Handler(provider.GetRequiredService().GetHandler()) + .Telemetry(instrumentation.CreateEndpoint(Options())).Settle(context => + { + if (!recover && context.Features.Get>()?.Disposition.Kind != DispositionKind.DeadLetter) + throw new InvalidOperationException("Durable failure decision lost."); + entered.SetResult(); + return new(finished.Task); + }).Build(1); + var receive = new ReceivePipeline(consumer, new HeaderNames("cloudEvents:"), 1); + var pending = receive.ProcessAsync(new Incoming()).AsTask(); + // Do not hang the regression run when settlement is bypassed. + await Task.WhenAny(entered.Task, pending); + try + { + await Assert.That(entered.Task.IsCompleted).IsTrue(); + await Assert.That(capture.Values.Count(v => v.Name == "messaging.client.consumed.messages")).IsEqualTo(1); + await Assert.That(capture.Values.Any(v => v.Name == "messaging.process.duration")).IsFalse(); + } + finally { finished.TrySetResult(); } + await Assert.That((await pending).Kind).IsEqualTo(recover ? DispositionKind.Complete : DispositionKind.DeadLetter); + await Assert.That(attempts).IsEqualTo(2); + await Assert.That(logger.Entries.Count).IsEqualTo(recover ? 1 : 2); + await Assert.That(capture.Values.Single(v => v.Name == "messaging.process.duration").Tags["error.type"]).IsEqualTo("_OTHER"); + await Assert.That(capture.Values.Count(v => v.Name == "relayer.critical_time")).IsEqualTo(1); + } + [Test] public async Task Instruments_have_pinned_schema_units_types_and_bucket_advice() { @@ -588,19 +662,42 @@ private void Add(Instrument instrument, double value, ReadOnlySpan Scope, Dictionary State); private sealed class Logger : ILogger { + internal string? ThrowAt { get; init; } internal int ScopesStarted { get; private set; } internal IReadOnlyList>? CurrentScope { get; private set; } internal List Entries { get; } = []; - public bool IsEnabled(LogLevel logLevel) => true; + public bool IsEnabled(LogLevel logLevel) => ThrowAt == "enabled" ? throw new ApplicationException("logger") : true; public IDisposable? BeginScope(TState state) where TState : notnull { + if (ThrowAt == "scope") throw new ApplicationException("logger"); ScopesStarted++; CurrentScope = (IReadOnlyList>)(object)state; return new Scope(this); } - public void Log(LogLevel level, EventId id, TState state, Exception? error, Func formatter) => + public void Log(LogLevel level, EventId id, TState state, Exception? error, Func formatter) + { + if (ThrowAt == "log") throw new ApplicationException("logger"); Entries.Add(new(error, CurrentScope!.ToDictionary(), ((IEnumerable>)(object)state!).ToDictionary())); - private sealed class Scope(Logger owner) : IDisposable { public void Dispose() => owner.CurrentScope = null; } + } + private sealed class Scope(Logger owner) : IDisposable + { + public void Dispose() + { + owner.CurrentScope = null; + if (owner.ThrowAt == "dispose") throw new ApplicationException("logger"); + } + } + } + private sealed class Transport : ITransport + { + public string Name => "test"; + public TransportCapabilities GetCapabilities(string endpoint) => new() { DeadLetter = true }; + public ValueTask SendAsync(OutgoingMessage message, CancellationToken cancellationToken) => throw new NotSupportedException(); + public ValueTask SendBatchAsync(ReadOnlyMemory messages, CancellationToken cancellationToken) => throw new NotSupportedException(); + public ValueTask ApplyTopologyAsync(TopologyMode mode, CancellationToken cancellationToken) => throw new NotSupportedException(); + public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; + public ValueTask DisposeAsync() => default; } private sealed class ExternalScopeProvider : ILoggerProvider, ISupportExternalScope, ILogger { From 01e73ade0d643fca05b7072b7c85559bdd64107d Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:31:39 +0000 Subject: [PATCH 7/8] fix: preserve native settlement marker after failure handling (#84) --- docs/decisions.md | 2 +- src/Relayer/Pipeline/ReceivePipeline.cs | 2 +- tests/Relayer.Tests/TelemetryTests.cs | 12 ++++++++---- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index c5e365c69..7201c4c34 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -211,7 +211,7 @@ Superseded by [D24](#d24-capabilities-are-valued-and-declared-per-endpoint). - W3C trace context is propagated in native headers. - The outbox captures trace context at enqueue time. - Processing duration is measured after settlement. -- Generated failure logs open an identity scope only around the log call. `LoggerFactory` allocates when it pushes an external scope, so successful deliveries must not open a Relayer scope. Failure scopes contain read-only snapshots rather than pooled context references, allowing providers to retain them for asynchronous export. +- Generated failure logs open an identity scope only around the log call. `LoggerFactory` allocates when it pushes an external scope, so successful deliveries must not open a Relayer scope. Failure scopes contain read-only snapshots rather than pooled context references, allowing providers to retain them for asynchronous export. Logging provider failures must not replace the delivery error or bypass durable failure handling. - Enrichers are supported. ## D16. Topology is declared; default mode is Validate diff --git a/src/Relayer/Pipeline/ReceivePipeline.cs b/src/Relayer/Pipeline/ReceivePipeline.cs index 2bb509641..08ba1541c 100644 --- a/src/Relayer/Pipeline/ReceivePipeline.cs +++ b/src/Relayer/Pipeline/ReceivePipeline.cs @@ -41,7 +41,7 @@ public async ValueTask ProcessAsync(TIncoming message, Cancellation using var context = _consumer.RentContext(state, cancellationToken); context.Features.Set(state.Native); await _consumer.ProcessAsync(context).ConfigureAwait(false); - return context.FailureDisposition ?? state.Native.Disposition; + return state.Native.Disposition; } finally { diff --git a/tests/Relayer.Tests/TelemetryTests.cs b/tests/Relayer.Tests/TelemetryTests.cs index 24ff68de0..e68eebe41 100644 --- a/tests/Relayer.Tests/TelemetryTests.cs +++ b/tests/Relayer.Tests/TelemetryTests.cs @@ -38,9 +38,10 @@ public async Task Throwing_logger_does_not_skip_durable_failure_handling(string } [Test] - [Arguments(false)] - [Arguments(true)] - public async Task Executable_failure_pipeline_records_delivery_and_settles_after_durability(bool recover) + [Arguments(false, false)] + [Arguments(true, false)] + [Arguments(false, true)] + public async Task Executable_failure_pipeline_records_delivery_and_settles_after_durability(bool recover, bool manuallySettled) { var logger = new Logger(); using var instrumentation = new RelayerInstrumentation(new LoggerFactory(logger)); @@ -64,6 +65,7 @@ public async Task Executable_failure_pipeline_records_delivery_and_settles_after { if (!recover && context.Features.Get>()?.Disposition.Kind != DispositionKind.DeadLetter) throw new InvalidOperationException("Durable failure decision lost."); + if (manuallySettled) context.Features.Get>()!.Disposition = Disposition.SettledByHandler; entered.SetResult(); return new(finished.Task); }).Build(1); @@ -78,7 +80,9 @@ public async Task Executable_failure_pipeline_records_delivery_and_settles_after await Assert.That(capture.Values.Any(v => v.Name == "messaging.process.duration")).IsFalse(); } finally { finished.TrySetResult(); } - await Assert.That((await pending).Kind).IsEqualTo(recover ? DispositionKind.Complete : DispositionKind.DeadLetter); + var expected = recover ? DispositionKind.Complete : DispositionKind.DeadLetter; + if (manuallySettled) expected = DispositionKind.SettledByHandler; + await Assert.That((await pending).Kind).IsEqualTo(expected); await Assert.That(attempts).IsEqualTo(2); await Assert.That(logger.Entries.Count).IsEqualTo(recover ? 1 : 2); await Assert.That(capture.Values.Single(v => v.Name == "messaging.process.duration").Tags["error.type"]).IsEqualTo("_OTHER"); From 8177812ac5303519bad34f389f460215ff1cacde Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 12:38:44 +0000 Subject: [PATCH 8/8] fix: clear recovered retry failure metrics (#84) --- docs/decisions.md | 1 + docs/telemetry.md | 4 +- src/Relayer/Pipeline/ConsumePipeline.cs | 1 + tests/Relayer.Tests/TelemetryTests.cs | 49 ++++++++++++++++++++++++- 4 files changed, 52 insertions(+), 3 deletions(-) diff --git a/docs/decisions.md b/docs/decisions.md index 7201c4c34..7708f388e 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -211,6 +211,7 @@ Superseded by [D24](#d24-capabilities-are-valued-and-declared-per-endpoint). - W3C trace context is propagated in native headers. - The outbox captures trace context at enqueue time. - Processing duration is measured after settlement. +- Immediate retries share one delivery duration. A retry that completes handling, scope disposal and buffered send flushing clears earlier failures from the duration's `error.type`; each failed attempt is still logged. Unrecovered failures retain the tag, including after durable dead-letter handling or subsequent delivery-token cancellation. A settlement error marks the duration as failed; delivery-token cancellation alone does not. - Generated failure logs open an identity scope only around the log call. `LoggerFactory` allocates when it pushes an external scope, so successful deliveries must not open a Relayer scope. Failure scopes contain read-only snapshots rather than pooled context references, allowing providers to retain them for asynchronous export. Logging provider failures must not replace the delivery error or bypass durable failure handling. - Enrichers are supported. diff --git a/docs/telemetry.md b/docs/telemetry.md index 48bac42da..4a66e5cfe 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -27,9 +27,9 @@ var consumer = new ConsumePipelineBuilder( The settlement callback reads the transport's native feature and its disposition. It runs only after durable processing, failure handling and async scope disposal succeed. It must honor `SettledByHandler`, use the broker's native semantics, and record its native operation with a separate endpoint recorder (`OperationName = "complete"`, `"ack"`, `"commit"`, etc.). `context.Services` is unavailable after scope disposal. A settlement error propagates to the receive loop without re-entering failure handling. If settlement runs outside this callback, its duration cannot be included in the process metric. Amortized commits stay outside per-message processing, as design §8.2 requires. -Both consumer constructors support telemetry and settlement. With an executable `FailurePipeline`, the native feature receives the resolved failure disposition before the settlement callback runs. Immediate retries share one delivery count and duration, including all attempt scopes, send flushes, durable failure work and settlement. Any processing failure in those attempts retains `error.type`, even when a later retry succeeds. +Both consumer constructors support telemetry and settlement. With an executable `FailurePipeline`, the native feature receives the resolved failure disposition before the settlement callback runs. Immediate retries share one delivery count and duration, including all attempt scopes, send flushes, durable failure work and settlement. A successful retry clears earlier failures from the duration's `error.type` only after its scope disposal and buffered send flush succeed. Each failed attempt is still logged. A later settlement error marks the duration as failed. -The consumer records one `messaging.client.consumed.messages` measurement per delivery and a `messaging.process.duration` measurement after settlement. Processing failures, including ones durably handled by the failure pipeline, mark the duration with `error.type = "_OTHER"`. Actual exception objects are retained in logs. This bounded fallback avoids runtime type lookups and message-derived metric dimensions. Delivery-token cancellation still counts as a delivery and records duration, but does not add `error.type`. If handling already failed before settlement is canceled, the duration retains that earlier failure. Cancellation before receive adaptation starts is not a delivery. +The consumer records one `messaging.client.consumed.messages` measurement per delivery and a `messaging.process.duration` measurement after settlement. Unrecovered processing failures, including ones durably dead-lettered or otherwise handled by the failure pipeline, mark the duration with `error.type = "_OTHER"`. Actual exception objects are retained in logs. This bounded fallback avoids runtime type lookups and message-derived metric dimensions. Delivery-token cancellation still counts as a delivery and records duration, but does not add `error.type`. If handling already failed and no retry recovered before cancellation, the duration retains that earlier failure. Cancellation before receive adaptation starts is not a delivery. Other execution components use the same recorder methods: `RecordSent` counts messages attempted at the broker, including failed attempts, but never an outbox enqueue. `RecordDuration` selects the process histogram only for `OperationName = "process"`; other operations use the client-operation histogram. Durations and dispatch lag use seconds. Outbox dispatch, retry, inbox, circuit and transport implementations call the corresponding recorder only when the actual action occurs. The current core exposes those recording seams; it does not infer retries or dead-letter success from a classifier decision. `RecordConsumerLag` accepts the native client's lag calculation. Circuit values are 0 closed, 1 open and 2 half-open. diff --git a/src/Relayer/Pipeline/ConsumePipeline.cs b/src/Relayer/Pipeline/ConsumePipeline.cs index bf7d9cea2..6845f8b95 100644 --- a/src/Relayer/Pipeline/ConsumePipeline.cs +++ b/src/Relayer/Pipeline/ConsumePipeline.cs @@ -249,6 +249,7 @@ private async ValueTask ProcessWithFailuresAsync(DefaultMessageContext context) // Dispose the successful scope before allowing sends to escape. A flush failure propagates: // some sends may have succeeded, so do not retry the handler or return a settlement decision. await context.SendBuffer.FlushAsync(context.CancellationToken).ConfigureAwait(false); + failure = null; break; } context.SendBuffer.Clear(); diff --git a/tests/Relayer.Tests/TelemetryTests.cs b/tests/Relayer.Tests/TelemetryTests.cs index e68eebe41..62d9d768c 100644 --- a/tests/Relayer.Tests/TelemetryTests.cs +++ b/tests/Relayer.Tests/TelemetryTests.cs @@ -85,10 +85,57 @@ public async Task Executable_failure_pipeline_records_delivery_and_settles_after await Assert.That((await pending).Kind).IsEqualTo(expected); await Assert.That(attempts).IsEqualTo(2); await Assert.That(logger.Entries.Count).IsEqualTo(recover ? 1 : 2); - await Assert.That(capture.Values.Single(v => v.Name == "messaging.process.duration").Tags["error.type"]).IsEqualTo("_OTHER"); + var duration = capture.Values.Single(v => v.Name == "messaging.process.duration"); + await Assert.That(duration.Tags.ContainsKey("error.type")).IsEqualTo(!recover); + if (!recover) await Assert.That(duration.Tags["error.type"]).IsEqualTo("_OTHER"); await Assert.That(capture.Values.Count(v => v.Name == "relayer.critical_time")).IsEqualTo(1); } + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Executable_retry_cancellation_retains_only_unrecovered_failure_metrics(bool recover) + { + var logger = new Logger(); + using var instrumentation = new RelayerInstrumentation(new LoggerFactory(logger)); + using var capture = new Capture(instrumentation); + await using var provider = Provider(services => { services.AddSingleton(); services.AddSingleton(); }); + using var cancellation = new CancellationTokenSource(); + var attempts = 0; + provider.GetRequiredService().Handle = context => + { + if (++attempts == 1) throw new InvalidOperationException("handler"); + if (!recover) + { + cancellation.Cancel(); + context.CancellationToken.ThrowIfCancellationRequested(); + } + return default; + }; + var failures = new FailurePipeline(provider, "test", "orders", "billing", + new() { RetryDelays = new[] { TimeSpan.Zero }, Jitter = 0 }); + var settlements = 0; + var pipeline = new ConsumePipelineBuilder(provider.GetRequiredService(), + provider.GetRequiredService(), new Serializer(), failures) + .Handler(provider.GetRequiredService().GetHandler()) + .Telemetry(instrumentation.CreateEndpoint(Options())).Settle(context => + { + settlements++; + cancellation.Cancel(); + context.CancellationToken.ThrowIfCancellationRequested(); + return default; + }).Build(1); + using var context = pipeline.RentContext(Message(), cancellation.Token); + await Assert.That(async () => await pipeline.ProcessAsync(context)).Throws(); + await Assert.That(attempts).IsEqualTo(2); + await Assert.That(settlements).IsEqualTo(recover ? 1 : 0); + await Assert.That(logger.Entries.Count).IsEqualTo(1); + await Assert.That(capture.Values.Count(v => v.Name == "messaging.client.consumed.messages")).IsEqualTo(1); + var duration = capture.Values.Single(v => v.Name == "messaging.process.duration"); + await Assert.That(duration.Tags.ContainsKey("error.type")).IsEqualTo(!recover); + if (!recover) await Assert.That(duration.Tags["error.type"]).IsEqualTo("_OTHER"); + } + [Test] public async Task Instruments_have_pinned_schema_units_types_and_bucket_advice() {