Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions src/Testing/CoreTests/Runtime/handler_pipeline_failure_containment.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using NSubstitute;
using Shouldly;
using Wolverine;
using Wolverine.Logging;
using Wolverine.Runtime;
using Wolverine.Transports;
using Xunit;

namespace CoreTests.Runtime;

// GH-3111: a single un-recoverable envelope (classically an OutOfMemoryException from an unbounded
// deserialization) must not be able to take the host down. The pipeline's last-resort recovery
// (ack the message out of the way + log) itself allocates, so when the original failure is memory
// exhaustion it can re-throw. If that escapes InvokeAsync it faults the receiver loop, stops the
// listener, and the host exits cleanly (code 0) into a broker redelivery / crash loop. These tests
// pin the containment: RecoverFromFailedProcessingAsync never throws, whatever the recovery path does.
public class handler_pipeline_failure_containment
{
private readonly Envelope theEnvelope = new() { Id = Guid.NewGuid() };
private readonly Exception theOriginalFailure = new OutOfMemoryException("deserialization blew the heap");
private readonly IMessageTracker theTracker = Substitute.For<IMessageTracker>();

[Fact]
public async Task happy_path_acks_the_message_and_logs_the_exception()
{
var channel = new FakeChannel();
var logger = new RecordingLogger();

await Should.NotThrowAsync(() => HandlerPipeline
.RecoverFromFailedProcessingAsync(channel, theEnvelope, theOriginalFailure, theTracker, logger, null)
.AsTask());

channel.CompleteCalls.ShouldBe(1);
theTracker.Received(1).LogException(theOriginalFailure, theEnvelope.Id);
// No containment error logged when recovery succeeds.
logger.ErrorCalls.ShouldBe(0);
}

[Fact]
public async Task contains_oom_thrown_by_complete_async()
{
var channel = new FakeChannel { CompleteThrows = new OutOfMemoryException("ack also OOMs") };
var logger = new RecordingLogger();

await Should.NotThrowAsync(() => HandlerPipeline
.RecoverFromFailedProcessingAsync(channel, theEnvelope, theOriginalFailure, theTracker, logger, null)
.AsTask());

// The recovery failure is contained and reported, not rethrown.
logger.ErrorCalls.ShouldBe(1);
}

[Fact]
public async Task contains_oom_thrown_while_logging_the_original_exception()
{
var channel = new FakeChannel();
theTracker.When(t => t.LogException(Arg.Any<Exception>(), Arg.Any<object?>(), Arg.Any<string>()))
.Do(_ => throw new OutOfMemoryException("structured logging OOMs"));
var logger = new RecordingLogger();

await Should.NotThrowAsync(() => HandlerPipeline
.RecoverFromFailedProcessingAsync(channel, theEnvelope, theOriginalFailure, theTracker, logger, null)
.AsTask());

channel.CompleteCalls.ShouldBe(1);
logger.ErrorCalls.ShouldBe(1);
}

[Fact]
public async Task never_throws_even_when_the_contained_logging_itself_throws()
{
// Worst case at the true memory ceiling: even the minimal containment log allocates and fails.
var channel = new FakeChannel { CompleteThrows = new OutOfMemoryException() };
var logger = new ThrowingLogger();

await Should.NotThrowAsync(() => HandlerPipeline
.RecoverFromFailedProcessingAsync(channel, theEnvelope, theOriginalFailure, theTracker, logger, null)
.AsTask());
}

private sealed class FakeChannel : IChannelCallback
{
public Exception? CompleteThrows { get; init; }
public int CompleteCalls { get; private set; }

public IHandlerPipeline? Pipeline => null;

public ValueTask CompleteAsync(Envelope envelope)
{
CompleteCalls++;
if (CompleteThrows != null) throw CompleteThrows;
return ValueTask.CompletedTask;
}

public ValueTask DeferAsync(Envelope envelope) => ValueTask.CompletedTask;
}

private sealed class RecordingLogger : ILogger
{
public int ErrorCalls { get; private set; }

public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func<TState, Exception?, string> formatter)
{
if (logLevel >= LogLevel.Error) ErrorCalls++;
}
}

private sealed class ThrowingLogger : ILogger
{
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func<TState, Exception?, string> formatter)
=> throw new OutOfMemoryException("even logging OOMs");
}
}
74 changes: 67 additions & 7 deletions src/Wolverine/Runtime/HandlerPipeline.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Diagnostics;
using JasperFx.Core;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.ObjectPool;
using Wolverine.Configuration;
using Wolverine.ErrorHandling;
Expand Down Expand Up @@ -93,13 +94,12 @@ public async Task InvokeAsync(Envelope envelope, IChannelCallback channel, Activ
}
catch (Exception e)
{
await channel.CompleteAsync(envelope).ConfigureAwait(false);

// Gotta get the message out of here because it's something that
// could never be handled
Logger.LogException(e, envelope.Id);

activity?.SetStatus(ActivityStatusCode.Error, e.GetType().Name);
// The pipeline's last line of defense. Containment lives in a guarded helper so a
// failure in the recovery path itself (e.g. an OutOfMemoryException re-thrown by the
// allocating CompleteAsync / logging calls) can never escape InvokeAsync, fault the
// receiver loop, and silently stop the listener. See GH-3111.
await RecoverFromFailedProcessingAsync(channel, envelope, e, Logger, _runtime.Logger, activity)
.ConfigureAwait(false);
}
finally
{
Expand All @@ -112,6 +112,66 @@ public async Task InvokeAsync(Envelope envelope, IChannelCallback channel, Activ
}
}

/// <summary>
/// The pipeline's final, allocation-safe recovery step. Normal failures are acked out of the way
/// and logged exactly as before; the difference is that if that recovery work itself throws — which
/// happens when the original failure is resource exhaustion, because <see cref="IChannelCallback.CompleteAsync"/>
/// and structured logging both allocate at the memory ceiling — the failure is contained here instead of
/// escaping <c>InvokeAsync</c>. An exception escaping the pipeline faults the receiver loop, stops the
/// listener, and lets the host exit cleanly (exit code 0), which an orchestrator reads as success and
/// restarts straight back into the same un-acked poison message → permanent crash loop. A single
/// un-recoverable envelope must never take the whole host down. See GH-3111.
/// </summary>
internal static async ValueTask RecoverFromFailedProcessingAsync(
IChannelCallback channel,
Envelope envelope,
Exception exception,
IMessageTracker tracker,
ILogger logger,
Activity? activity)
{
try
{
// Gotta get the message out of here because it's something that
// could never be handled
await channel.CompleteAsync(envelope).ConfigureAwait(false);

tracker.LogException(exception, envelope.Id);

activity?.SetStatus(ActivityStatusCode.Error, exception.GetType().Name);
}
catch (Exception recoveryFailure)
{
// The recovery path itself failed — almost always because the original failure was an
// OutOfMemoryException and CompleteAsync / structured logging also allocate. Swallow it so
// it cannot escape InvokeAsync and stop the listener; the broker will redeliver the
// still-un-acked envelope, but the host stays up and keeps processing other messages.
TryLogContainedFailure(logger, envelope, exception, recoveryFailure, activity);
}
}

private static void TryLogContainedFailure(ILogger logger, Envelope envelope, Exception original,
Exception recoveryFailure, Activity? activity)
{
try
{
var fatal = original is OutOfMemoryException || recoveryFailure is OutOfMemoryException;

logger.LogError(recoveryFailure,
"Wolverine could not recover from a {Severity} failure while processing envelope {Id} " +
"(original failure: {Original}). The message was not acknowledged or dead-lettered and may be " +
"redelivered by the broker; the listener is being kept alive to avoid a poison-message crash loop. See GH-3111.",
fatal ? "fatal resource-exhaustion" : "cascading", envelope.Id, original.GetType().Name);

activity?.SetStatus(ActivityStatusCode.Error, original.GetType().Name);
}
catch
{
// Even minimal structured logging allocates and can itself fail at the memory ceiling.
// There is nothing more we can safely do here; never let the containment path throw.
}
}

public async ValueTask<IContinuation> TryDeserializeEnvelope(Envelope envelope)
{
if (envelope.Message != null) return NullContinuation.Instance;
Expand Down
Loading