diff --git a/docs/decisions.md b/docs/decisions.md index fbfaa48b8..9bcff418c 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -85,6 +85,7 @@ To change a decision, add a new entry that supersedes it rather than editing his | [D72](#d72-handler-registration-belongs-to-the-consumer) | Handler registration belongs to the consumer | Accepted | | [D73](#d73-postgresql-retryable-outbox-sends-retain-durable-eligibility) | PostgreSQL retryable outbox sends retain durable eligibility | Accepted | | [D74](#d74-portable-consumer-failure-declarations) | Portable consumer failure declarations | Accepted | +| [D75](#d75-failure-diagnostics-are-bounded) | Failure diagnostics are bounded | Accepted | --- @@ -1763,3 +1764,15 @@ budget. Repair such configuration through the existing dead-letter redrive workf Delay options are bindable arrays. `FailureOptions` retains its convenience constructor and provides a real public parameterless constructor for `OptionsFactory`. Its properties use public setters as a narrow exception to the init-only options convention: the .NET configuration binding source generator skips init-only properties when binding an existing instance through `AddOptions().Bind(section)`. This preserves standard Options-pattern binding and Native AOT support; policies are captured and composed at startup, and reload does not rebuild consumers. `CopyTimeout` uses null for its 30-second default so configuration binding preserves missing settings without accepting an explicit zero timeout. Null `RetryDelays` selects D69's default sequence at composition; empty disables it. This avoids the configuration binder appending configured entries to a pre-populated default array. In-memory native redelivery retains failure headers per queued message or per log-group receiver, preventing attempt/history resets without sharing mutable consumer state across groups. In-memory consumers use only native redelivery for retries, including manual settlement requests. Scheduled-copy and outbox redelivery fallbacks are rejected when the requested delay exceeds `MaxRedeliveryDelay`: sending another message to the source would fan out to unrelated log groups and could wait for admission credit still owned by the current delivery. Native redelivery retains both the group and that credit. Dead-letter copies to a separate configured endpoint remain supported. + +## D75. Failure diagnostics are bounded + +**Status:** Accepted; supersedes D10's every-attempt diagnostic retention guarantee. + +**Context.** Unbounded exception history can exceed native message/header limits and prevent durable poison settlement. The history is Relayer-owned metadata (D10); native clients cannot bound its application JSON for us. Existing native settlement, copy and Pub/Sub attribute splitting remain in use. + +**Decision.** Retain at most eight attempts, preserving first and latest, with 2,048-character stacks and 1,024-character diagnostic fields/native dead-letter error descriptions. Limit generated JSON to 16 KiB using its actual UTF-8 byte length including escaping. Remove intermediate attempts before shortening text. Mark incomplete history with `Truncated`; preserve total attempt counts and first/last timestamps. Incoming malformed or larger-than-16-KiB history is replaced with truncated history before deserialization. + +Copies budget against the destination's declared `MaxMessageBytes`, subtracting portable body, headers and ordering key. Native settlements budget body and failure headers against the source declaration, because the lazy header SPI cannot enumerate original properties. If even the first/latest summary cannot fit, omit only the history header and retain counters. Native overhead, hidden properties, native callbacks and attribute counts remain broker-enforced; application data is never removed to make room. Native send failure still prevents settlement. + +**Consequences.** Full exception diagnostics belong in application logs/traces. All new work runs on failure/manual settlement paths; the successful receive and send paths are unchanged. See the site's [failure handling contract](../website/docs/guides/failure-handling.md). diff --git a/docs/design.md b/docs/design.md index 82692724e..8e89f6b6a 100644 --- a/docs/design.md +++ b/docs/design.md @@ -427,8 +427,8 @@ Copies preserve the original identity and creation context. Native redelivery di `FailureHeaders` that the adapter **must persist before releasing the original**. Native dead-letter dispositions carry the same history in `DeadLetterInfo.Headers`. Their owned metadata survives pooled-context disposal. Adapters must not advertise native redelivery if they cannot preserve that metadata. History records the -original ID (null for a missing ID), total failed attempts, first/last failure times, and each attempt's consumer, -host, exception type, message and stack. Error metadata uses generated JSON, including under Native AOT. +original ID (null for a missing ID), total failed attempts, first/last failure times, and retained attempts' consumer, +host, exception type, message and stack. D75 bounds diagnostics while retaining total counts. Error metadata uses generated JSON, including under Native AOT. Malformed failure counters are permanent envelope errors; corrupt history is replaced so poison messages can still reach the dead-letter destination. History construction and exception type diagnostics run only on failure. @@ -443,7 +443,7 @@ dead-letter requests. See [Failure handling](https://relayer.tomlonghurst.dev/do for the call site, precedence and buffered-send contract. -- **Error metadata** goes on the dead-lettered message: the original message ID, exception type, message and stack trace for **every** attempt (Rebus #1154), attempt count, first and last failure time, consumer name, and host. SQS visibility retries preserve immutable native attributes: their final copy retains previously stored history and the current delivery’s in-process failures; earlier visibility-delivery exceptions are unavailable from SQS (D67). +- **Error metadata** goes on the dead-lettered message: the original message ID, exception type, message and stack trace for retained attempts (D75) (Rebus #1154), attempt count, first and last failure time, consumer name, and host. SQS visibility retries preserve immutable native attributes: their final copy retains previously stored history and the current delivery’s in-process failures; earlier visibility-delivery exceptions are unavailable from SQS (D67). - **Redrive API:** `IDeadLetterManager` provides `List`, `Peek`, `Redrive(filter)`, and `Purge`, backed by native broker mechanisms. Queue redrive settles an original after an acknowledged send; Kafka redrive commits a dedicated group offset after that send and leaves the original subject to native retention. Kafka purge deletes scanned partition prefixes with native `DeleteRecords`, never arbitrary records. See the [site roadmap](../website/docs/roadmap.md) for implemented transports and optional endpoint/CLI status. - **Circuit breaker:** when the failure rate of a consumer crosses a threshold, Relayer **pauses the consumer natively** (Kafka `Pause`, ASB processor stop, RabbitMQ consumer cancel) instead of burning messages into the DLQ (SlimMessageBus #454). It then half-opens with a probe message. - **Retries never duplicate side effects.** Outbox rows written by a failed attempt are rolled back with the transaction. Without a transaction, sends made during a failed attempt are buffered and discarded (Rebus #1198, Rebus.PostgreSql #53). diff --git a/src/Relayer.GooglePubSub/GooglePubSubBuilderExtensions.cs b/src/Relayer.GooglePubSub/GooglePubSubBuilderExtensions.cs index 0b8446124..50d8239d5 100644 --- a/src/Relayer.GooglePubSub/GooglePubSubBuilderExtensions.cs +++ b/src/Relayer.GooglePubSub/GooglePubSubBuilderExtensions.cs @@ -86,11 +86,11 @@ internal static OutgoingMessage Copy(Google.Cloud.PubSub.V1.PubsubMessage messag { var count = 0; foreach (var header in message.Attributes) - if (!header.Key.StartsWith("goog", StringComparison.Ordinal)) count++; + if (!header.Key.StartsWith("goog", StringComparison.Ordinal) && !GooglePubSubFailureHeaders.IsHistory(header.Key)) count++; var headers = new KeyValuePair[count]; var index = 0; foreach (var header in message.Attributes) - if (!header.Key.StartsWith("goog", StringComparison.Ordinal)) + if (!header.Key.StartsWith("goog", StringComparison.Ordinal) && !GooglePubSubFailureHeaders.IsHistory(header.Key)) headers[index++] = new(header.Key, new(header.Value)); return new("copy", message.Data.Memory, headers, message.OrderingKey.Length == 0 ? null : new WireString(message.OrderingKey)); } diff --git a/src/Relayer.GooglePubSub/GooglePubSubFailureHeaders.cs b/src/Relayer.GooglePubSub/GooglePubSubFailureHeaders.cs index f353c7518..daa822729 100644 --- a/src/Relayer.GooglePubSub/GooglePubSubFailureHeaders.cs +++ b/src/Relayer.GooglePubSub/GooglePubSubFailureHeaders.cs @@ -14,6 +14,9 @@ internal static class GooglePubSubFailureHeaders private const int MaxAttributes = 100; private const int MaxValueBytes = 1024; + internal static bool IsHistory(string name) => name == FailureHeaders.History || name == Parts || + name.StartsWith(Prefix, StringComparison.Ordinal); + internal static void Write(PubsubMessage message, string history) { List? previous = null; diff --git a/src/Relayer/Failures/FailureMetadata.cs b/src/Relayer/Failures/FailureMetadata.cs index 09ea3e48a..a8ad93a03 100644 --- a/src/Relayer/Failures/FailureMetadata.cs +++ b/src/Relayer/Failures/FailureMetadata.cs @@ -1,5 +1,6 @@ using System.Buffers.Text; using System.Globalization; +using System.Text; using System.Text.Json; using System.Text.Json.Serialization; @@ -12,7 +13,7 @@ public static class FailureHeaders public const string Attempts = "relayer.failure.attempts"; /// Number of scheduled/native redeliveries already requested. public const string Redeliveries = "relayer.failure.redeliveries"; - /// JSON error history, including original identity, location and every attempt's exception. + /// Bounded JSON error history, including original identity, location and retained exceptions. public const string History = "relayer.failure.history"; /// The handler's reason when manual dead-lettering requires a durable copy. public const string DeadLetterReason = "relayer.dead_letter.reason"; @@ -26,6 +27,7 @@ internal sealed class FailureHistory public DateTimeOffset FirstFailureTime { get; set; } public DateTimeOffset LastFailureTime { get; set; } public int AttemptCount { get; set; } + public bool Truncated { get; set; } public List Attempts { get; set; } = []; } @@ -45,6 +47,11 @@ internal partial class FailureJsonContext : JsonSerializerContext; internal static class FailureMetadata { + internal const int MaxAttempts = 8; + internal const int MaxHistoryBytes = 16 * 1024; + internal const int MaxStackTraceChars = 2048; + private const int MaxFieldChars = 1024; + internal static int ReadCount(MessageHeaders headers, string name) { if (!headers.TryGetValue(name, out var value)) return 0; @@ -58,12 +65,16 @@ internal static int ReadCount(MessageHeaders headers, string name) internal static FailureHistory ReadHistory(MessageContext context, string consumer) { - if (context.Headers.TryGetValue(FailureHeaders.History, out var value)) + if (context.Headers.TryGetValue(FailureHeaders.History, out var value) && ByteCount(value) <= MaxHistoryBytes) { try { var history = JsonSerializer.Deserialize(value.ToString(), FailureJsonContext.Default.FailureHistory); - if (history is not null && history.Attempts is not null) return history; + if (history is not null && history.Attempts is not null) + { + Normalize(history); + return history; + } } catch (JsonException) { } // Invalid error metadata must not prevent a poison message from reaching the dead-letter path. @@ -71,7 +82,8 @@ internal static FailureHistory ReadHistory(MessageContext context, string consum string? id = null; try { id = context.MessageId; } catch (MessageEnvelopeException) { } - return new() { OriginalMessageId = id, Consumer = consumer, Host = Environment.MachineName }; + return new() { OriginalMessageId = id, Consumer = consumer, Host = Environment.MachineName, + Truncated = context.Headers.TryGetValue(FailureHeaders.History, out _) }; } internal static void Record(DefaultMessageContext context, Exception error, string consumer, TimeProvider time) @@ -81,6 +93,11 @@ internal static void Record(DefaultMessageContext context, Exception error, stri if (history.Attempts.Count == 0) history.FirstFailureTime = now; history.LastFailureTime = now; history.AttemptCount = context.Attempt; + if (history.Attempts.Count == MaxAttempts) + { + history.Attempts.RemoveAt(1); + history.Truncated = true; + } history.Attempts.Add(new() { Attempt = context.Attempt, Time = now, Consumer = consumer, Host = Environment.MachineName, @@ -88,26 +105,133 @@ internal static void Record(DefaultMessageContext context, Exception error, stri ExceptionType = error.GetType().FullName ?? error.GetType().Name, Message = error.Message, StackTrace = error.StackTrace, }); + Normalize(history); } internal static KeyValuePair[] SettlementHeaders(DefaultMessageContext context, int redeliveries, - string? reason = null) + string? reason = null, long? maxBytes = null) { var headers = new List>(4) { new(FailureHeaders.Attempts, new(context.Attempt.ToString(CultureInfo.InvariantCulture))), new(FailureHeaders.Redeliveries, new(redeliveries.ToString(CultureInfo.InvariantCulture))), }; - if (context.FailureHistory is { } history) - headers.Add(new(FailureHeaders.History, new(JsonSerializer.Serialize(history, FailureJsonContext.Default.FailureHistory)))); - else if (context.Headers.TryGetValue(FailureHeaders.History, out var prior)) - headers.Add(new(FailureHeaders.History, prior)); if (reason is not null) headers.Add(new(FailureHeaders.DeadLetterReason, new(reason))); + var history = context.FailureHistory; + if (history is null && context.Headers.TryGetValue(FailureHeaders.History, out _)) + history = context.FailureHistory = ReadHistory(context, ""); + if (history is not null) + { + var remaining = maxBytes ?? long.MaxValue; + foreach (var header in headers) remaining -= Encoding.UTF8.GetByteCount(header.Key) + ByteCount(header.Value); + remaining -= Encoding.UTF8.GetByteCount(FailureHeaders.History); + var json = Serialize(history, remaining); + if (json is not null) headers.Add(new(FailureHeaders.History, new(json))); + } return headers.ToArray(); } - internal static KeyValuePair[] Headers(DefaultMessageContext context, int redeliveries) - => [new(FailureHeaders.Attempts, new(context.Attempt.ToString(CultureInfo.InvariantCulture))), - new(FailureHeaders.Redeliveries, new(redeliveries.ToString(CultureInfo.InvariantCulture))), - new(FailureHeaders.History, new(JsonSerializer.Serialize(context.FailureHistory!, FailureJsonContext.Default.FailureHistory)))]; + internal static KeyValuePair[] Headers(DefaultMessageContext context, int redeliveries, long? maxBytes = null) + => SettlementHeaders(context, redeliveries, maxBytes: maxBytes); + + // Copies know all portable fields. Native settlement only exposes lazy named headers: its broker + // remains authoritative for envelope overhead and other native properties. + internal static void FitCopyHistory(List> headers, in OutgoingMessage original, long? maximum, FailureHistory? history) + { + if (maximum is null) return; + var remaining = maximum.Value - original.Body.Length; + if (original.OrderingKey is { } key) remaining -= ByteCount(key); + var historyIndex = -1; + for (var i = 0; i < headers.Count; i++) + { + var header = headers[i]; + remaining -= Encoding.UTF8.GetByteCount(header.Key); + if (header.Key == FailureHeaders.History) historyIndex = i; + else remaining -= ByteCount(header.Value); + } + if (historyIndex < 0 || history is null || ByteCount(headers[historyIndex].Value) <= remaining) return; + var json = Serialize(history, remaining); + if (json is null) headers.RemoveAt(historyIndex); + else headers[historyIndex] = new(FailureHeaders.History, new(json)); + } + + internal static string Description(Exception error) + { + var message = error.Message; + if (message.Length <= MaxFieldChars) return message; + var length = char.IsHighSurrogate(message[MaxFieldChars - 1]) ? MaxFieldChars - 1 : MaxFieldChars; + return message[..length]; + } + + internal static int ByteCount(WireString value) => value.Text is { } text ? Encoding.UTF8.GetByteCount(text) : value.Utf8.Length; + + private static void Normalize(FailureHistory history) + { + while (history.Attempts.Count > MaxAttempts) + { + history.Attempts.RemoveAt(1); + history.Truncated = true; + } + history.OriginalMessageId = Limit(history.OriginalMessageId, MaxFieldChars, history); + history.Consumer = Limit(history.Consumer, MaxFieldChars, history) ?? ""; + history.Host = Limit(history.Host, MaxFieldChars, history) ?? ""; + for (var i = history.Attempts.Count - 1; i >= 0; i--) + { + var attempt = history.Attempts[i]; + if (attempt is null) + { + history.Attempts.RemoveAt(i); + history.Truncated = true; + continue; + } + attempt.Consumer = Limit(attempt.Consumer, MaxFieldChars, history) ?? ""; + attempt.Host = Limit(attempt.Host, MaxFieldChars, history) ?? ""; + attempt.ExceptionType = Limit(attempt.ExceptionType, MaxFieldChars, history) ?? ""; + attempt.Message = Limit(attempt.Message, MaxFieldChars, history) ?? ""; + attempt.StackTrace = Limit(attempt.StackTrace, MaxStackTraceChars, history); + } + } + + private static string? Limit(string? value, int chars, FailureHistory history) + { + if (value is null || value.Length <= chars) return value; + history.Truncated = true; + // Do not split a UTF-16 surrogate pair at the truncation boundary. + if (chars > 0 && char.IsHighSurrogate(value[chars - 1])) chars--; + return value[..chars]; + } + + private static string? Serialize(FailureHistory history, long budget) + { + Normalize(history); + budget = Math.Min(budget, MaxHistoryBytes); + while (budget > 0) + { + var json = JsonSerializer.Serialize(history, FailureJsonContext.Default.FailureHistory); + if (Encoding.UTF8.GetByteCount(json) <= budget) return json; + history.Truncated = true; + // Retain the first and latest exceptions ahead of intermediate attempts. + if (history.Attempts.Count > 2) history.Attempts.RemoveAt(1); + else + { + var changed = false; + foreach (var attempt in history.Attempts) + { + changed |= !string.IsNullOrEmpty(attempt.StackTrace) || attempt.Message.Length > 0 || + attempt.Consumer.Length > 0 || attempt.Host.Length > 0 || attempt.ExceptionType.Length > 0; + attempt.StackTrace = Limit(attempt.StackTrace, (attempt.StackTrace?.Length ?? 0) / 2, history); + attempt.Message = Limit(attempt.Message, attempt.Message.Length / 2, history)!; + attempt.Consumer = Limit(attempt.Consumer, attempt.Consumer.Length / 2, history)!; + attempt.Host = Limit(attempt.Host, attempt.Host.Length / 2, history)!; + attempt.ExceptionType = Limit(attempt.ExceptionType, attempt.ExceptionType.Length / 2, history)!; + } + changed |= !string.IsNullOrEmpty(history.OriginalMessageId) || history.Consumer.Length > 0 || history.Host.Length > 0; + history.OriginalMessageId = Limit(history.OriginalMessageId, (history.OriginalMessageId?.Length ?? 0) / 2, history); + history.Consumer = Limit(history.Consumer, history.Consumer.Length / 2, history)!; + history.Host = Limit(history.Host, history.Host.Length / 2, history)!; + if (!changed) return null; + } + } + return null; + } } diff --git a/src/Relayer/Failures/FailurePipeline.cs b/src/Relayer/Failures/FailurePipeline.cs index 340420b6d..56c4c165c 100644 --- a/src/Relayer/Failures/FailurePipeline.cs +++ b/src/Relayer/Failures/FailurePipeline.cs @@ -26,6 +26,7 @@ public sealed class FailurePipeline private readonly bool _nativeDeadLetter; private readonly bool _nativeRedeliveryOnly; private readonly TransportCapabilities _capabilities; + private readonly long? _deadLetterMaxBytes; /// Validates native paths and available fallback executors for this consumer's complete policy. public FailurePipeline(IServiceProvider services, string transportName, string source, string consumer, @@ -85,7 +86,7 @@ internal FailurePipeline(IServiceProvider services, string transportName, string { if (string.IsNullOrWhiteSpace(_options.DeadLetterEndpoint) || copy is null) throw Invalid("DeadLetter", "Enable native DeadLetter with error metadata, or configure DeadLetterEndpoint and a message copy executor."); - validator.GetCapabilities(_transport, _options.DeadLetterEndpoint); + _deadLetterMaxBytes = validator.GetCapabilities(_transport, _options.DeadLetterEndpoint)?.MaxMessageBytes; } _paths = new RedeliveryPath[_redeliveries.Length]; for (var i = 0; i < _paths.Length; i++) _paths[i] = ResolveRedelivery(_redeliveries[i]); @@ -123,7 +124,7 @@ internal async ValueTask HandleSettlementAsync(DefaultMessageContext context, Di { var path = ResolveRedelivery(request.Delay); // A manual retry is not an exception. Preserve prior error history without inventing a failure. - var headers = FailureMetadata.SettlementHeaders(context, checked(context.Redeliveries + 1)); + var headers = FailureMetadata.SettlementHeaders(context, checked(context.Redeliveries + 1), maxBytes: path == RedeliveryPath.Native ? MetadataBudget(context) : null); if (path == RedeliveryPath.Native) context.FailureDisposition = Disposition.Redeliver(request.Delay, headers); else @@ -135,7 +136,7 @@ await CopyAsync(context, _source, _time.GetUtcNow() + request.Delay, headers, } else { - var headers = FailureMetadata.SettlementHeaders(context, context.Redeliveries, request.DeadLetter.Reason); + var headers = FailureMetadata.SettlementHeaders(context, context.Redeliveries, request.DeadLetter.Reason, _nativeDeadLetter ? MetadataBudget(context, System.Text.Encoding.UTF8.GetByteCount(request.DeadLetter.Reason)) : null); if (_nativeDeadLetter) context.FailureDisposition = Disposition.DeadLettered(new(request.DeadLetter.Reason, headers: headers)); else @@ -170,7 +171,7 @@ internal async ValueTask HandleAsync(DefaultMessageContext context, Exception er var redelivery = context.Redeliveries; if (action == FailureAction.Retry && redelivery < _paths.Length) { - var headers = FailureMetadata.Headers(context, redelivery + 1); + var headers = FailureMetadata.Headers(context, redelivery + 1, _paths[redelivery] == RedeliveryPath.Native ? MetadataBudget(context) : null); var delay = Jitter(_redeliveries[redelivery]); if (_paths[redelivery] == RedeliveryPath.Native) context.FailureDisposition = Disposition.Redeliver(delay, headers); @@ -182,9 +183,10 @@ await CopyAsync(context, _source, _time.GetUtcNow() + delay, headers, } return; } - var deadHeaders = FailureMetadata.Headers(context, redelivery); + var description = FailureMetadata.Description(error); + var deadHeaders = FailureMetadata.Headers(context, redelivery, _nativeDeadLetter ? MetadataBudget(context, System.Text.Encoding.UTF8.GetByteCount(description) + System.Text.Encoding.UTF8.GetByteCount("Processing failed")) : null); if (_nativeDeadLetter) - context.FailureDisposition = Disposition.DeadLettered(new("Processing failed", error.Message, deadHeaders)); + context.FailureDisposition = Disposition.DeadLettered(new("Processing failed", description, deadHeaders)); else { await CopyAsync(context, _options.DeadLetterEndpoint!, null, deadHeaders, false).ConfigureAwait(false); @@ -201,6 +203,8 @@ private async ValueTask CopyAsync(DefaultMessageContext context, string destinat var headers = new List>(original.Headers.Length + metadata.Length); foreach (var header in original.Headers.Span) { + // A deliberately omitted history must not resurrect an oversized incoming value. + if (header.Key == FailureHeaders.History) continue; var replaced = false; foreach (var replacement in metadata) { @@ -211,6 +215,8 @@ private async ValueTask CopyAsync(DefaultMessageContext context, string destinat if (!replaced) headers.Add(header); } headers.AddRange(metadata); + FailureMetadata.FitCopyHistory(headers, original, + destination == _source ? _capabilities.MaxMessageBytes : _deadLetterMaxBytes, context.FailureHistory); var copy = original.Forward(destination, headers.ToArray(), deliverAt); if (schedule) copy.ValidateForOutbox(); // Fallback work is on the error path. Its timeout covers the whole durable operation. @@ -223,5 +229,8 @@ private async ValueTask CopyAsync(DefaultMessageContext context, string destinat timeout.Token.ThrowIfCancellationRequested(); } + private long? MetadataBudget(DefaultMessageContext context, int nativeFieldBytes = 0) => + _capabilities.MaxMessageBytes is { } maximum ? Math.Max(0, maximum - context.Body.Length - nativeFieldBytes) : null; + private enum RedeliveryPath { Native, Copy, Outbox } } diff --git a/tests/Relayer.GooglePubSub.Tests/GooglePubSubFailureHeaderTests.cs b/tests/Relayer.GooglePubSub.Tests/GooglePubSubFailureHeaderTests.cs index 47ccd2a29..84e359dcd 100644 --- a/tests/Relayer.GooglePubSub.Tests/GooglePubSubFailureHeaderTests.cs +++ b/tests/Relayer.GooglePubSub.Tests/GooglePubSubFailureHeaderTests.cs @@ -22,6 +22,21 @@ public async Task Large_unicode_history_round_trips_losslessly_and_shorter_repla await Assert.That(message.Attributes[FailureHeaders.History]).IsEqualTo("short"); } + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Failure_copy_removes_all_old_history_before_budgeting_even_without_replacement(bool split) + { + var message = new PubsubMessage(); + message.Attributes["application"] = "preserved"; + GooglePubSubFailureHeaders.Write(message, new string('x', split ? 4096 : 32)); + message.Attributes[FailureHeaders.History + ".part.999"] = "orphan"; + var copy = GooglePubSubHostedService.Copy(message); + await Assert.That(copy.Headers.Length).IsEqualTo(1); + await Assert.That(copy.Headers.Span[0].Key).IsEqualTo("application"); + await Assert.That(copy.Headers.Span[0].Value.ToString()).IsEqualTo("preserved"); + } + [Test] public async Task Malformed_or_missing_parts_are_treated_as_missing_history() { diff --git a/tests/Relayer.Tests/FailureHistorySqsTests.cs b/tests/Relayer.Tests/FailureHistorySqsTests.cs new file mode 100644 index 000000000..fff29d288 --- /dev/null +++ b/tests/Relayer.Tests/FailureHistorySqsTests.cs @@ -0,0 +1,93 @@ +using System.Text; +using System.Text.Json; +using Amazon.Runtime; +using Amazon.SQS; +using Amazon.SQS.Model; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Relayer.AmazonSqs; +using Relayer.Transports; + +namespace Relayer.Tests; + +public sealed class FailureHistorySqsTests +{ + [Test] + public async Task Long_poison_history_reaches_a_size_limited_native_queue_before_source_deletion() + { + // Shared provisioning has its own five-minute budget; message assertions start after readiness. + var serviceUrl = await SharedBrokers.LocalStackUrlAsync(CancellationToken.None); + using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(3)); + var token = deadline.Token; + using var client = new AmazonSQSClient(new BasicAWSCredentials("test", "test"), new AmazonSQSConfig + { + ServiceURL = serviceUrl, AuthenticationRegion = "us-east-1", MaxErrorRetry = 0, + }); + var source = TestContext.Current!.Isolation.GetIsolatedName("history-source"); + var dead = TestContext.Current!.Isolation.GetIsolatedName("history-dead"); + var builder = Host.CreateApplicationBuilder(); + builder.Services.AddRelayer(relayer => + { + relayer.AddMessageTypesFromThisAssembly(); + relayer.AmazonSqs("history", sqs => + { + sqs.TopologyMode = TopologyMode.Provision; + sqs.Options.Configure(options => + { + options.SqsClient = client; + options.Queues.Add(new(source)); + options.Queues.Add(new(dead) { Attributes = new() { ["MaximumMessageSize"] = "4096" } }); + }); + sqs.Consume(source, consumer => + { + consumer.Handler(); + consumer.Options.ConfigureReceive = request => request.WaitTimeSeconds = 1; + consumer.Failures(new() { DeadLetterEndpoint = dead, RetryDelays = new TimeSpan[31], Jitter = 0 }); + }); + }); + }); + using var host = builder.Build(); + await host.StartAsync(token); + try + { + var transport = host.Services.GetServices().Single(t => t.Name == "history"); + await transport.SendAsync(new(source, "{}"u8.ToArray(), new KeyValuePair[] + { + new("ce_id", new("poison")), new("ce_type", new("failure.history.sqs;v=1")), + }), token); + var deadUrl = (await client.GetQueueUrlAsync(dead, token)).QueueUrl; + var result = await client.ReceiveMessageAsync(new ReceiveMessageRequest + { QueueUrl = deadUrl, WaitTimeSeconds = 20, MessageAttributeNames = ["All"] }, token); + var copy = result.Messages.Single(); + await Assert.That(copy.Body).IsEqualTo("{}"); + await Assert.That(copy.MessageAttributes[FailureHeaders.Attempts].StringValue).IsEqualTo("32"); + using var history = JsonDocument.Parse(copy.MessageAttributes[FailureHeaders.History].StringValue); + await Assert.That(history.RootElement.GetProperty("Truncated").GetBoolean()).IsTrue(); + var attempts = history.RootElement.GetProperty("Attempts"); + await Assert.That(attempts[0].GetProperty("Attempt").GetInt32()).IsEqualTo(1); + await Assert.That(attempts[attempts.GetArrayLength() - 1].GetProperty("Attempt").GetInt32()).IsEqualTo(32); + var size = Encoding.UTF8.GetByteCount(copy.Body); + foreach (var attribute in copy.MessageAttributes) + size += Encoding.UTF8.GetByteCount(attribute.Key) + Encoding.UTF8.GetByteCount(attribute.Value.DataType) + Encoding.UTF8.GetByteCount(attribute.Value.StringValue); + await Assert.That(size <= 4096).IsTrue(); + await host.StopAsync(token); + var sourceUrl = (await client.GetQueueUrlAsync(source, token)).QueueUrl; + var remaining = await client.GetQueueAttributesAsync(sourceUrl, ["ApproximateNumberOfMessages", "ApproximateNumberOfMessagesNotVisible"], token); + await Assert.That(remaining.Attributes["ApproximateNumberOfMessages"]).IsEqualTo("0"); + await Assert.That(remaining.Attributes["ApproximateNumberOfMessagesNotVisible"]).IsEqualTo("0"); + } + finally { await host.StopAsync(CancellationToken.None); } + } + + [Message("failure.history.sqs")] + public sealed class Payload; + public sealed class Handler : IHandler + { + public ValueTask HandleAsync(Payload message, MessageContext context, CancellationToken cancellationToken) => throw new Poison(); + } + private sealed class Poison : Exception + { + public override string Message => "poison " + new string('界', 10000); + public override string StackTrace => new('x', 200000); + } +} diff --git a/tests/Relayer.Tests/FailurePipelineTests.cs b/tests/Relayer.Tests/FailurePipelineTests.cs index c92561202..4d62b5f15 100644 --- a/tests/Relayer.Tests/FailurePipelineTests.cs +++ b/tests/Relayer.Tests/FailurePipelineTests.cs @@ -4,6 +4,7 @@ using System.Text.Json; using Microsoft.Extensions.DependencyInjection; using Relayer.Transports; +using Relayer.InMemory; namespace Relayer.Tests; @@ -966,6 +967,132 @@ public async Task Manual_retry_uses_durable_scheduler_and_preserves_prior_failur await Assert.That(history.RootElement.GetProperty("Attempts").GetArrayLength()).IsEqualTo(1); } + [Test] + public async Task History_bounds_keep_first_and_latest_attempts_across_redeliveries() + { + using var provider = Provider(new Transport { Capabilities = new() { DeadLetter = true, MaxRedeliveryDelay = TimeSpan.Zero } }); + provider.GetRequiredService().Invoke = _ => throw new LongFailure(); + var pipeline = Pipeline(provider, new() { RetryDelays = new TimeSpan[19], RedeliveryDelays = new[] { TimeSpan.Zero } }); + var first = await pipeline.ProcessAsync(new()); + var next = new Incoming(); + foreach (var pair in first.Headers.Span) next.Headers[pair.Key] = pair.Value.ToString(); + var final = await pipeline.ProcessAsync(next); + await Assert.That(final.DeadLetter.Description!.Length <= 1024).IsTrue(); + var json = final.DeadLetter.Headers.ToArray().Single(p => p.Key == FailureHeaders.History).Value.ToString(); + await Assert.That(Encoding.UTF8.GetByteCount(json) <= FailureMetadata.MaxHistoryBytes).IsTrue(); + using var history = JsonDocument.Parse(json); + var root = history.RootElement; + var attempts = root.GetProperty("Attempts"); + await Assert.That(root.GetProperty("Truncated").GetBoolean()).IsTrue(); + await Assert.That(root.GetProperty("AttemptCount").GetInt32()).IsEqualTo(40); + await Assert.That(attempts.GetArrayLength() <= FailureMetadata.MaxAttempts).IsTrue(); + await Assert.That(attempts[0].GetProperty("Attempt").GetInt32()).IsEqualTo(1); + await Assert.That(attempts[attempts.GetArrayLength() - 1].GetProperty("Attempt").GetInt32()).IsEqualTo(40); + foreach (var attempt in attempts.EnumerateArray()) + await Assert.That(attempt.GetProperty("StackTrace").GetString()!.Length <= FailureMetadata.MaxStackTraceChars).IsTrue(); + } + + [Test] + [Arguments(2048)] + [Arguments(256)] + public async Task Poison_with_large_exceptions_reaches_size_limited_dead_letter_destination(int maximum) + { + await using var transport = new InMemoryTransport("test", new Dictionary + { + ["source"] = new() { Capabilities = new() }, + ["destination"] = new(), + ["errors"] = new() { Capabilities = new() { MaxMessageBytes = maximum, OrderedByKey = true } }, + }); + using var provider = Provider(transport); + provider.GetRequiredService().Invoke = _ => throw new LongFailure(); + var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + transport.RegisterConsumer("errors", (delivery, _) => + { + received.TrySetResult(Snapshot.From(new("errors", delivery.Message.Body, delivery.Message.Headers, delivery.Message.OrderingKey))); + return new(Disposition.Complete); + }); + await transport.StartAsync(default); + try + { + var incoming = new Incoming(); + // Old versions could have persisted an oversized history. It must not be resurrected + // when the replacement cannot fit in the small destination. + incoming.Headers[FailureHeaders.History] = new string('x', 20000); + var result = await Pipeline(provider, new() { DeadLetterEndpoint = "errors", RetryDelays = new TimeSpan[39] }, Copy).ProcessAsync(incoming); + await Assert.That(result.Kind).IsEqualTo(DispositionKind.Complete); + var copy = await received.Task.WaitAsync(TimeSpan.FromSeconds(10)); + await Assert.That(copy.Body).IsEqualTo("{}"); + await Assert.That(copy.Headers["custom"]).IsEqualTo("preserved"); + await Assert.That(copy.Headers[FailureHeaders.Attempts]).IsEqualTo("40"); + if (maximum == 2048) + { + using var history = JsonDocument.Parse(copy.Headers[FailureHeaders.History]); + await Assert.That(history.RootElement.GetProperty("Truncated").GetBoolean()).IsTrue(); + await Assert.That(history.RootElement.GetProperty("Attempts")[0].GetProperty("Attempt").GetInt32()).IsEqualTo(1); + } + else await Assert.That(copy.Headers.ContainsKey(FailureHeaders.History)).IsFalse(); + } + finally { await transport.StopAsync(default); } + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Manual_settlement_bounds_preexisting_history(bool oversized) + { + using var provider = Provider(new Transport()); + provider.GetRequiredService().Invoke = context => + { + context.Features.GetRequired().DeadLetter("poison"); + return default; + }; + var incoming = new Incoming(); + var history = new FailureHistory { AttemptCount = 100 }; + for (var i = 1; i <= (oversized ? 100 : 20); i++) + history.Attempts.Add(new() { Attempt = i, StackTrace = new string('x', oversized ? 5000 : 100) }); + incoming.Headers[FailureHeaders.History] = JsonSerializer.Serialize(history, FailureJsonContext.Default.FailureHistory); + var result = await Pipeline(provider).ProcessAsync(incoming); + var json = result.DeadLetter.Headers.ToArray().Single(p => p.Key == FailureHeaders.History).Value.ToString(); + await Assert.That(Encoding.UTF8.GetByteCount(json) <= FailureMetadata.MaxHistoryBytes).IsTrue(); + using var parsed = JsonDocument.Parse(json); + await Assert.That(parsed.RootElement.GetProperty("Attempts").GetArrayLength() <= FailureMetadata.MaxAttempts).IsTrue(); + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task Native_dead_letter_budget_includes_reason_and_description(bool manual) + { + const int maximum = 640; + using var provider = Provider(new Transport { Capabilities = new() { DeadLetter = true, MaxMessageBytes = maximum } }); + provider.GetRequiredService().Invoke = context => + { + if (!manual) throw new InvalidOperationException(new string('界', 20)); + context.Features.GetRequired().DeadLetter(new string('界', 30)); + return default; + }; + var incoming = new Incoming(); + // A long incoming history forces the native settlement to shrink its replacement. + incoming.Headers[FailureHeaders.History] = JsonSerializer.Serialize(new FailureHistory + { + AttemptCount = 1, + Attempts = [new() { Attempt = 1, Message = new string('x', 1000) }], + }, FailureJsonContext.Default.FailureHistory); + var result = await Pipeline(provider, FailureOptions.None).ProcessAsync(incoming); + await Assert.That(result.Kind).IsEqualTo(DispositionKind.DeadLetter); + var bytes = Encoding.UTF8.GetByteCount("{}") + Encoding.UTF8.GetByteCount(result.DeadLetter.Reason) + + Encoding.UTF8.GetByteCount(result.DeadLetter.Description ?? ""); + foreach (var header in result.DeadLetter.Headers.ToArray()) + bytes += Encoding.UTF8.GetByteCount(header.Key) + Encoding.UTF8.GetByteCount(header.Value.ToString()); + await Assert.That(bytes <= maximum).IsTrue(); + } + + private sealed class LongFailure : Exception + { + public override string Message => new('界', 20000); + public override string StackTrace => string.Concat(Enumerable.Repeat("\"\\界😀\n", 20000)); + } + private static void Request(ISettlementFeature settlement, DispositionKind kind) { switch (kind) @@ -979,7 +1106,7 @@ private static void Request(ISettlementFeature settlement, DispositionKind kind) private static ValueTask Throw(MessageContext context) => throw new InvalidOperationException("failed attempt"); - private static ServiceProvider Provider(Transport transport, Action? configure = null) + private static ServiceProvider Provider(ITransport transport, Action? configure = null) { var services = new ServiceCollection(); services.AddSingleton(transport); diff --git a/website/docs/guides/failure-handling.md b/website/docs/guides/failure-handling.md index dec47667b..d36cf5c04 100644 --- a/website/docs/guides/failure-handling.md +++ b/website/docs/guides/failure-handling.md @@ -165,7 +165,7 @@ If a native circuit stop or recovery start fails, consumption stops and the fail ## Error history -Copies keep the original message ID and trace context. Dead-lettered and redelivered messages carry their failure history: the original ID, total failed attempts, first and last failure times, and for every attempt the consumer, host, exception type, message and stack trace. The history is serialized with generated JSON, so it works under Native AOT. SQS visibility retries cannot update native attributes: their retry budget uses the native receive count, and the final copy preserves stored history plus the current delivery’s in-process failures. Earlier visibility-delivery errors are unavailable from SQS; see [SQS receiving](../transports/amazon-sqs.md#receiving-and-durable-settlement). +Copies keep the original message ID and trace context. Dead-lettered and redelivered messages carry their failure history: the original ID, total failed attempts, first and last failure times, and retained attempts’ consumer, host, exception type, message and stack trace. History keeps at most eight attempts, retaining the first and latest, with stack traces limited to 2,048 characters and other diagnostic fields and the native dead-letter error description to 1,024 characters. The serialized UTF-8 JSON is capped at 16 KiB; `Truncated` indicates removed diagnostics. Size pressure removes intermediate attempts first, then shortens diagnostic text while retaining first/latest attempt numbers and times. Total attempt counts remain accurate. Copies further reduce history to fit the destination’s declared `MaxMessageBytes` after accounting for portable body, headers and ordering key. If even the first/latest summary cannot fit, only the history header is omitted; attempt and redelivery counters remain. Pub/Sub copies remove previous split history attributes before calculating this budget, including when no replacement history fits. Native settlement budgets the body, failure headers, dead-letter reason and error description against the source limit; native envelope overhead, hidden properties, header-count limits and undeclared size limits remain broker-enforced. Applications must leave room for those fields. Incoming history larger than 16 KiB or malformed JSON is replaced with a truncated history so poison handling can continue. The history is serialized with generated JSON, so it works under Native AOT. SQS visibility retries cannot update native attributes: their retry budget uses the native receive count, and the final copy preserves stored history plus the current delivery’s in-process failures. Earlier visibility-delivery errors are unavailable from SQS; see [SQS receiving](../transports/amazon-sqs.md#receiving-and-durable-settlement). Delivery remains at-least-once: a crash between sending a copy and completing the original can duplicate it. diff --git a/website/docs/transports/amazon-sqs.md b/website/docs/transports/amazon-sqs.md index b1b9f9966..9e5ccf70d 100644 --- a/website/docs/transports/amazon-sqs.md +++ b/website/docs/transports/amazon-sqs.md @@ -84,7 +84,7 @@ Visibility retries round positive delays up to whole seconds. Their ceiling is t SQS visibility changes cannot update attributes. The binding combines `ApproximateReceiveCount - 1` with any redelivery count on a previous durable copy, so retry policies terminate without a process-local retry cache. Previously stored history is preserved; the eventual copy adds the current delivery's in-process failure history. Errors from earlier visibility deliveries cannot be reconstructed from SQS (contributor decision D67). -SQS redrive cannot attach application failure metadata. `Failure.DeadLetterEndpoint` is required and must name a separately declared queue of the same standard/FIFO kind. The existing failure pipeline sends a copy with original identity, body, attributes, trace context and group key, then deletes the source only after that send succeeds. Copy or settlement failures leave the source available for native redelivery; duplicates are possible. Reserve room within SQS's ten-attribute limit for up to four failure attributes, and within the destination's native message-size limit for error history. These limits apply to externally produced messages too. If a copy cannot fit, Relayer retains the original and logs the failure instead of dropping attributes, truncating error history, or changing the body. Configure native `RedrivePolicy` as the broker safety net for messages that cannot be copied; native redrive preserves the original attributes but cannot add failure metadata. Native binary/typed attributes are preserved in direct failure copies with a native callback; these callbacks cannot be persisted by the outbox scheduler, which rejects such copies without deleting the original. FIFO copies preserve the native deduplication identity when the source or destination envelope identity is missing, cannot be used as a native SQS deduplication token (1–128 ASCII alphanumeric or punctuation characters, without spaces), or is a native typed attribute rather than an exact `String` attribute. Unusable identity attributes remain unchanged in the native copy and cannot overwrite the fallback. This fallback also requires a non-persistable native callback. Standard fair-queue copies preserve native `MessageGroupId` through the same non-persistable callback without requesting portable ordering. Text-only copies with both identities and no standard-queue group remain persistable. +SQS redrive cannot attach application failure metadata. `Failure.DeadLetterEndpoint` is required and must name a separately declared queue of the same standard/FIFO kind. The existing failure pipeline sends a copy with original identity, body, attributes, trace context and group key, then deletes the source only after that send succeeds. Copy or settlement failures leave the source available for native redelivery; duplicates are possible. Reserve room within SQS's ten-attribute limit for up to four failure attributes, and within the destination's native message-size limit for error history. These limits apply to externally produced messages too. Error history is bounded and shortened to the declared destination size budget as described in [failure handling](../guides/failure-handling.md). Native attribute type bytes and properties applied by native callbacks still count toward SQS’s size limit. If the copy still cannot fit, Relayer retains the original and logs the failure; it preserves application attributes and the body. Configure native `RedrivePolicy` as the broker safety net for messages that cannot be copied; native redrive preserves the original attributes but cannot add failure metadata. Native binary/typed attributes are preserved in direct failure copies with a native callback; these callbacks cannot be persisted by the outbox scheduler, which rejects such copies without deleting the original. FIFO copies preserve the native deduplication identity when the source or destination envelope identity is missing, cannot be used as a native SQS deduplication token (1–128 ASCII alphanumeric or punctuation characters, without spaces), or is a native typed attribute rather than an exact `String` attribute. Unusable identity attributes remain unchanged in the native copy and cannot overwrite the fallback. This fallback also requires a non-persistable native callback. Standard fair-queue copies preserve native `MessageGroupId` through the same non-persistable callback without requesting portable ordering. Text-only copies with both identities and no standard-queue group remain persistable. ## Health