From d66b0992054014cbd5ecda76257f098c488ab9fa Mon Sep 17 00:00:00 2001 From: Daniel Dror Date: Thu, 29 Oct 2026 10:39:16 -0700 Subject: [PATCH] Fix HTTP/2 hang when a reused stream's producer is left scheduled (#69690) Http2FrameWriter skipped producers whose response had already completed without clearing Http2OutputProducer._isScheduled. A stream WINDOW_UPDATE racing a response's final write can schedule the producer again after ObserveDataAndState cleared the flag, so that queue entry was dropped with the flag still set. StreamReset doesn't reset the flag, so the next request that reused the pooled stream could never schedule its HEADERS, DATA or trailers, and its aborts were never processed. Unschedule a completed producer under its lock when the frame writer skips it, and continue with the next producer. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Stephen Halter --- .../src/Internal/Http2/Http2FrameWriter.cs | 9 +- .../src/Internal/Http2/Http2OutputProducer.cs | 17 ++ .../Http2/Http2ConnectionTests.cs | 166 ++++++++++++++++++ 3 files changed, 191 insertions(+), 1 deletion(-) diff --git a/src/Servers/Kestrel/Core/src/Internal/Http2/Http2FrameWriter.cs b/src/Servers/Kestrel/Core/src/Internal/Http2/Http2FrameWriter.cs index 426f1c7b31c7..56534ee7e4db 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Http2/Http2FrameWriter.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Http2/Http2FrameWriter.cs @@ -179,8 +179,15 @@ private async Task WriteToOutputPipe() { // We need to handle the case where aborts can be scheduled while this loop is running and might be on the way to complete // the reader. - while (_channel.Reader.TryRead(out var producer) && !producer.CompletedResponse) + while (_channel.Reader.TryRead(out var producer)) { + // The producer can also be scheduled after its final write was observed, e.g. by a racing stream window update. + // Unschedule it so it can be scheduled again if its stream is pooled and reused. + if (producer.TryUnscheduleCompletedResponse()) + { + continue; + } + try { var reader = producer.PipeReader; diff --git a/src/Servers/Kestrel/Core/src/Internal/Http2/Http2OutputProducer.cs b/src/Servers/Kestrel/Core/src/Internal/Http2/Http2OutputProducer.cs index 142f8ba226dc..92a2fef15a5b 100644 --- a/src/Servers/Kestrel/Core/src/Internal/Http2/Http2OutputProducer.cs +++ b/src/Servers/Kestrel/Core/src/Internal/Http2/Http2OutputProducer.cs @@ -95,6 +95,23 @@ public bool CompletedResponse } } + // Called by the frame writer after dequeuing this producer. Returns true if the response has already completed, so there's + // nothing left to write. Checking and clearing _isScheduled under the same lock as Schedule() ensures a reused stream can't + // be left with _isScheduled set and no queued write. + internal bool TryUnscheduleCompletedResponse() + { + lock (_dataWriterLock) + { + if (!_completedResponse) + { + return false; + } + + _isScheduled = false; + return true; + } + } + // Useful for debugging the scheduling state in the debugger internal (int, long, State, State, long) SchedulingState => (Stream.StreamId, _unconsumedBytes, _unobservedState, _currentState, _streamWindow); diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/Http2ConnectionTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/Http2ConnectionTests.cs index 7f2029c6a655..2f247740448d 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/Http2ConnectionTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/Http2/Http2ConnectionTests.cs @@ -722,6 +722,172 @@ await ExpectAsync(Http2FrameType.HEADERS, AssertConnectionNoError(); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task StreamPool_ScheduledAfterResponseCompleted_PooledStreamReusedAndResponseSent(bool largeResponse) + { + var responseBody = new byte[largeResponse ? Http2PeerSettings.MinAllowedMaxFrameSize * 2 : 11]; + var appCompletedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + await InitializeConnectionAsync(async context => + { + if (context.Features.Get().StreamId == 1) + { + return; + } + + if (largeResponse) + { + await context.Response.Body.WriteAsync(responseBody); + } + else + { + // Buffer the small response so the app completes without waiting for it to be written. + context.Response.BodyWriter.Write(responseBody); + } + + context.Response.AppendTrailer("CustomName", "Custom Value"); + appCompletedTcs.SetResult(); + }); + + await StartStreamAsync(1, _browserRequestHeaders, endStream: true); + + await ExpectAsync(Http2FrameType.HEADERS, + withLength: 36, + withFlags: (byte)(Http2HeadersFrameFlags.END_HEADERS | Http2HeadersFrameFlags.END_STREAM), + withStreamId: 1); + + await WaitForAllStreamsAsync().DefaultTimeout(); + + var stream = _connection._streams[1]; + var output = (Http2OutputProducer)stream.Output; + Assert.True(output.CompletedResponse); + + // Simulate a late schedule, such as one from a stream WINDOW_UPDATE that raced the end of the response. + output.Schedule(); + + // TriggerTick will trigger the stream to be returned to the pool so we can assert it + TriggerTick(); + + Assert.Equal(1, _connection.StreamPool.Count); + Assert.True(_connection.StreamPool.TryPeek(out var pooledStream)); + Assert.Same(stream, pooledStream); + + // The pooled stream is reused for this request. + await StartStreamAsync(3, _browserRequestHeaders, endStream: true); + + await ExpectAsync(Http2FrameType.HEADERS, + withLength: 2, + withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS, + withStreamId: 3); + + for (var remaining = responseBody.Length; remaining > 0; remaining -= Http2PeerSettings.MinAllowedMaxFrameSize) + { + await ExpectAsync(Http2FrameType.DATA, + withLength: Math.Min(remaining, Http2PeerSettings.MinAllowedMaxFrameSize), + withFlags: (byte)Http2DataFrameFlags.NONE, + withStreamId: 3); + } + + await ExpectAsync(Http2FrameType.HEADERS, + withLength: 25, + withFlags: (byte)(Http2HeadersFrameFlags.END_HEADERS | Http2HeadersFrameFlags.END_STREAM), + withStreamId: 3); + + await appCompletedTcs.Task.DefaultTimeout(); + await WaitForAllStreamsAsync().DefaultTimeout(); + + TriggerTick(); + + Assert.Equal(1, _connection.StreamPool.Count); + Assert.True(_connection.StreamPool.TryPeek(out pooledStream)); + Assert.Same(stream, pooledStream); + + await StopConnectionAsync(expectedLastStreamId: 3, ignoreNonGoAwayFrames: false); + AssertConnectionNoError(); + } + + [Fact] + public async Task StreamPool_ScheduledDuringFinalWrite_PooledStreamReusedAndResponseSent() + { + // The final write of the first response fills the output buffer, so its flush can't complete until the client reads it. + _serviceContext.ServerOptions.Limits.MaxResponseBufferSize = 1024; + + await InitializeConnectionAsync(async context => + { + if (context.Features.Get().StreamId == 1) + { + // Buffer the response so it's written by the same write that completes the response. + context.Response.BodyWriter.Write(new byte[4096]); + return; + } + + await context.Response.WriteAsync("Hello World"); + context.Response.AppendTrailer("CustomName", "Custom Value"); + }); + + await StartStreamAsync(1, _browserRequestHeaders, endStream: true); + + // Wait for the final write to be flushed, but don't read it yet. + var readResult = await _pair.Application.Input.ReadAsync().AsTask().DefaultTimeout(); + _pair.Application.Input.AdvanceTo(readResult.Buffer.Start); + + var stream = _connection._streams[1]; + var output = (Http2OutputProducer)stream.Output; + Assert.False(output.CompletedResponse); + + // TryUpdateStreamWindow() calls ScheduleResumeFromWindowUpdate() after releasing the producer's lock, so a stream + // WINDOW_UPDATE can schedule the producer after its final write was observed but before the response is completed. + output.ScheduleResumeFromWindowUpdate(); + + await ExpectAsync(Http2FrameType.HEADERS, + withLength: 32, + withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS, + withStreamId: 1); + await ExpectAsync(Http2FrameType.DATA, + withLength: 4096, + withFlags: (byte)Http2DataFrameFlags.END_STREAM, + withStreamId: 1); + + await WaitForAllStreamsAsync().DefaultTimeout(); + Assert.True(output.CompletedResponse); + + // TriggerTick will trigger the stream to be returned to the pool so we can assert it + TriggerTick(); + + Assert.Equal(1, _connection.StreamPool.Count); + Assert.True(_connection.StreamPool.TryPeek(out var pooledStream)); + Assert.Same(stream, pooledStream); + + // The pooled stream is reused for this request. + await StartStreamAsync(3, _browserRequestHeaders, endStream: true); + + await ExpectAsync(Http2FrameType.HEADERS, + withLength: 2, + withFlags: (byte)Http2HeadersFrameFlags.END_HEADERS, + withStreamId: 3); + await ExpectAsync(Http2FrameType.DATA, + withLength: 11, + withFlags: (byte)Http2DataFrameFlags.NONE, + withStreamId: 3); + await ExpectAsync(Http2FrameType.HEADERS, + withLength: 25, + withFlags: (byte)(Http2HeadersFrameFlags.END_HEADERS | Http2HeadersFrameFlags.END_STREAM), + withStreamId: 3); + + await WaitForAllStreamsAsync().DefaultTimeout(); + + TriggerTick(); + + Assert.Equal(1, _connection.StreamPool.Count); + Assert.True(_connection.StreamPool.TryPeek(out pooledStream)); + Assert.Same(stream, pooledStream); + + await StopConnectionAsync(expectedLastStreamId: 3, ignoreNonGoAwayFrames: false); + AssertConnectionNoError(); + } + [Fact] public async Task Frame_Received_OverMaxSize_FrameError() {