Skip to content

Kestrel occasionally losing zero-size GRPC responses #53736

Closed

Description

@pjc50

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

After upgrading from dotnet 6 to dotnet 8, we started observing intermittent failures. Trying dotnet 7 also has the same failures.

Unfortunately this bug is extremely intermittent. We have not been able to create a minimal reproduction case. So far it has only been observed on Mac systems with Java GRPC clients. I've not been able to even trigger it on my desktop, only on CI systems. It is also very timing-sensitive; adding logging to either client or server tends to slow it down just enough for the bug not to manifest. Sorry.

There is only one client, with a thread making requests, a thread making healthcheck calls, and a thread processing a long-lived stream of events structured as an infinite stream of GRPC streaming responses. The failure is roughly four minutes in, and roughly at stream 256 (but not exactly! and it varies).

Once the response is lost the RPC that made it times out 30 seconds later with DEADLINE_EXCEEDED. However, in the meantime, healthcheck calls from the other thread work just fine.

By setting the log level to Trace I was able to obtain this:

Connection id "0HN12DQ56A4EB" received HEADERS frame for stream ID 243 with length 25 and flags END_HEADERS, PRIORITY.
Connection id "0HN12DQ56A4EB" received DATA frame for stream ID 243 with length 108 and flags END_STREAM.
Request starting HTTP/2 POST http://127.0.0.1:9091/StudioLinkProtocol.StudioLinkService/SetDeviceDescription - application/grpc -
All hosts are allowed.
3 candidate(s) found for the request path '/StudioLinkProtocol.StudioLinkService/SetDeviceDescription'
Endpoint 'gRPC - /StudioLinkProtocol.StudioLinkService/SetDeviceDescription' with route pattern '/StudioLinkProtocol.StudioLinkService/SetDeviceDescription' is valid for the request path '/StudioLinkProtocol.StudioLinkService/SetDeviceDescription'
Endpoint 'gRPC - Unimplemented method for StudioLinkProtocol.StudioLinkService' with route pattern 'StudioLinkProtocol.StudioLinkService/{unimplementedMethod:grpcunimplemented}' is valid for the request path '/StudioLinkProtocol.StudioLinkService/SetDeviceDescription'
Endpoint 'gRPC - Unimplemented service' with route pattern '{unimplementedService}/{unimplementedMethod:grpcunimplemented}' is valid for the request path '/StudioLinkProtocol.StudioLinkService/SetDeviceDescription'
Request matched endpoint 'gRPC - /StudioLinkProtocol.StudioLinkService/SetDeviceDescription'
The endpoint does not specify the IRequestSizeLimitMetadata.
Executing endpoint 'gRPC - /StudioLinkProtocol.StudioLinkService/SetDeviceDescription'
Request deadline timeout of 00:00:29.9999450 started.
Reading message.
Connection id "0HN12DQ56A4EB", Request id "0HN12DQ56A4EB:000000F3": started reading request body.
Connection id "0HN12DQ56A4EB", Request id "0HN12DQ56A4EB:000000F3": done reading request body.
Deserializing 103 byte message to 'StudioLinkProtocol.SetDeviceDescriptionFile'.
Received message.
Sending message.
Serialized 'StudioLinkProtocol.OperationResult' to 0 byte message.
Message sent.
Request deadline stopped.
Executed endpoint 'gRPC - /StudioLinkProtocol.StudioLinkService/SetDeviceDescription'
Request finished HTTP/2 POST http://127.0.0.1:9091/StudioLinkProtocol.StudioLinkService/SetDeviceDescription - 200 - application/grpc 50.2121ms

Expected Behavior

After that I would expect to see

Connection id "0HN12DQ56A4EB" sending HEADERS frame for stream ID 243 with length 4 and flags END_HEADERS.
Connection id "0HN12DQ56A4EB" sending DATA frame for stream ID 243 with length 5 and flags NONE.
Connection id "0HN12DQ56A4EB" sending HEADERS frame for stream ID 243 with length 1 and flags END_STREAM, END_HEADERS.

However there are no such messages, and eventually the client gives up and sends

Connection id "0HN12DQ56A4EB" received RST_STREAM frame for stream ID 243 with length 4 and flags 0x0.

Steps To Reproduce

We do not have a minimal reproduction case for this.

Exceptions (if any)

No response

.NET Version

8.0.101

Anything else?

Grpc.AspNetCore 2.59.0
MacOS 13.6.3 BuildVersion: 22G436 (Ventura)

Activity

  1. ghost added
    area-networking
    on Jan 31, 2024
  2. pjc50 commented on Jan 31, 2024

    @pjc50
    Author

    It is possible that the preceding request is relevant, which transfers a large amount of data including a couple of window updates, settings, and ping frames.

    Connection id "0HN12DQ56A4EB" sending DATA frame for stream ID 241 with length 16384 and flags NONE.
    Connection id "0HN12DQ56A4EB" sending DATA frame for stream ID 241 with length 9510 and flags NONE.
    Connection id "0HN12DQ56A4EB" received PING frame for stream ID 0 with length 8 and flags NONE.
    Connection id "0HN12DQ56A4EB" sending PING frame for stream ID 0 with length 8 and flags ACK.
    Connection id "0HN12DQ56A4EB" received WINDOW_UPDATE frame for stream ID 0 with length 4 and flags 0x0.
    Connection id "0HN12DQ56A4EB" received WINDOW_UPDATE frame for stream ID 241 with length 4 and flags 0x0.
    Connection id "0HN12DQ56A4EB" received WINDOW_UPDATE frame for stream ID 0 with length 4 and flags 0x0.
    Connection id "0HN12DQ56A4EB" received SETTINGS frame for stream ID 0 with length 6 and flags NONE.
    Connection id "0HN12DQ56A4EB" sending SETTINGS frame for stream ID 0 with length 0 and flags ACK.
    Connection id "0HN12DQ56A4EB" sending DATA frame for stream ID 241 with length 16384 and flags NONE.
    (repeated many times)
    Connection id "0HN12DQ56A4EB" sending DATA frame for stream ID 241 with length 16384 and flags NONE.
    Connection id "0HN12DQ56A4EB" sending DATA frame for stream ID 241 with length 9510 and flags NONE.
    Connection id "0HN12DQ56A4EB" received PING frame for stream ID 0 with length 8 and flags NONE.
    Connection id "0HN12DQ56A4EB" sending PING frame for stream ID 0 with length 8 and flags ACK.
    Connection id "0HN12DQ56A4EB" received WINDOW_UPDATE frame for stream ID 241 with length 4 and flags 0x0.
    Connection id "0HN12DQ56A4EB" received WINDOW_UPDATE frame for stream ID 0 with length 4 and flags 0x0.
    Connection id "0HN12DQ56A4EB" received WINDOW_UPDATE frame for stream ID 241 with length 4 and flags 0x0.
    Connection id "0HN12DQ56A4EB" sending DATA frame for stream ID 241 with length 16384 and flags NONE.
    Connection id "0HN12DQ56A4EB" sending DATA frame for stream ID 241 with length 16384 and flags NONE.
    Connection id "0HN12DQ56A4EB" sending DATA frame for stream ID 241 with length 16384 and flags NONE.
    Connection id "0HN12DQ56A4EB" sending DATA frame for stream ID 241 with length 16384 and flags NONE.
    Connection id "0HN12DQ56A4EB" sending DATA frame for stream ID 241 with length 5732 and flags NONE.
    Connection id "0HN12DQ56A4EB" sending HEADERS frame for stream ID 241 with length 1 and flags END_STREAM, END_HEADERS.
    Connection id "0HN12DQ56A4EB" received SETTINGS frame for stream ID 0 with length 6 and flags NONE.
    Connection id "0HN12DQ56A4EB" sending SETTINGS frame for stream ID 0 with length 0 and flags ACK.
    Connection id "0HN12DQ56A4EB" received PING frame for stream ID 0 with length 8 and flags NONE.
    Connection id "0HN12DQ56A4EB" sending PING frame for stream ID 0 with length 8 and flags ACK.

  3. added
    area-grpc
    on Jan 31, 2024
  4. Tratcher commented on Feb 2, 2024

    @Tratcher
    Member

    Receiving repeated SETTINGS frames is suspicious. Any chance you can get a trace of those? The connection logging middleware would help, or wireshark if it's decrypted.
    https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/connection-middleware?view=aspnetcore-8.0#connection-logging

  5. pjc50 commented on Feb 2, 2024

    @pjc50
    Author

    I think that's possible, will see on Monday.

  6. pjc50 commented on Feb 5, 2024

    @pjc50
    Author

    Wireshark output for the last SETTINGS before the failure and its ack:

    Frame 30651: 71 bytes on wire (568 bits), 71 bytes captured (568 bits) on interface lo0, id 0
    Null/Loopback
    Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1
    Transmission Control Protocol, Src Port: 61800, Dst Port: 9091, Seq: 9766, Ack: 2903349, Len: 15
    HyperText Transfer Protocol 2
    Stream: SETTINGS, Stream ID: 0, Length 6
    Length: 6
    Type: SETTINGS (4)
    Flags: 0x00
    0... .... .... .... .... .... .... .... = Reserved: 0x0
    .000 0000 0000 0000 0000 0000 0000 0000 = Stream Identifier: 0
    Settings - Initial Windows size : 1559026
    Settings Identifier: Initial Windows size (4)
    Initial Window Size: 1559026

    Frame 30658: 65 bytes on wire (520 bits), 65 bytes captured (520 bits) on interface lo0, id 0
    Null/Loopback
    Internet Protocol Version 4, Src: 127.0.0.1, Dst: 127.0.0.1

    Transmission Control Protocol, Src Port: 9091, Dst Port: 61800, Seq: 2974777, Ack: 9781, Len: 9
    HyperText Transfer Protocol 2
    Stream: SETTINGS, Stream ID: 0, Length 0
    Length: 0
    Type: SETTINGS (4)
    Flags: 0x01, ACK
    0... .... .... .... .... .... .... .... = Reserved: 0x0
    .000 0000 0000 0000 0000 0000 0000 0000 = Stream Identifier: 0

    Selected packets dotnet issue.zip

  7. pjc50 commented on Feb 5, 2024

    @pjc50
    Author

    Settings packets only.zip
    All 72 SETTINGS packets from that TCP stream.

  8. Tratcher commented on Feb 5, 2024

    @Tratcher
    Member

    Weird, the client keeps sending settings frames with increasing Initial Windows Size on the same connection. It starts at 1048576 and gets as high as 5093722. That's not illegal, just highly unusual. The server ack's so it should be fine. It should also only affect new requests, not ongoing streams. I wonder if a buffer gets dropped/replaced somewhere?

  9. added this to the Backlog milestone on Jul 23, 2025
  10. noocyte commented on Sep 21, 2026

    @noocyte

    We hit what looks like the same bug on ASP.NET Core 10.0.12 (Linux, Kestrel h2c, Grpc.AspNetCore 2.83.0, .NET SocketsHttpHandler/Grpc.Net.Client 2.83.0 as the client). It is not limited to zero-size responses: our lost response is about 430 KB. Rate: 1 lost response in about 26,700 HTTP/2 requests in a 19-minute run across 37 server processes. It only ever hits the service whose responses span several stream windows.

    Kestrel trace for the lost stream (149). The preceding stream on the same connection (147) is a 430 KB response: 27 DATA frames, stream WINDOW_UPDATEs interleaved, trailers, and then four more WINDOW_UPDATEs for 147 arrive after its trailers were sent. 284 ms later stream 149 arrives, the app completes, hosting logs Request finished 200, and Kestrel never sends a single frame for 149. The next stream (151), 300 ms later, is served normally.

    11:01:59.984 received HEADERS frame for stream ID 147 with length 376 and flags END_HEADERS.
    11:01:59.987 sending HEADERS frame for stream ID 147 with length 34 and flags END_HEADERS.
                 ... 27 DATA frames for 147, 11 received WINDOW_UPDATE for 147 in between ...
    11:01:59.988 sending DATA frame for stream ID 147 with length 11868 and flags NONE.
    11:01:59.988 sending HEADERS frame for stream ID 147 with length 1 and flags END_STREAM, END_HEADERS.
    11:01:59.988 received WINDOW_UPDATE frame for stream ID 147 with length 4 and flags 0x0.   (x4)
    11:02:00.272 received HEADERS frame for stream ID 149 with length 376 and flags END_HEADERS.
    11:02:00.272 received DATA frame for stream ID 149 with length 135 and flags NONE.
    11:02:00.272 received DATA frame for stream ID 149 with length 0 and flags END_STREAM.
    11:02:00.272 Request starting HTTP/2 POST http://localhost:5343/templateservice.TemplateService/Get - application/grpc null
    11:02:00.275 Request finished HTTP/2 POST http://localhost:5343/templateservice.TemplateService/Get - 200 null application/grpc 3.1234ms
                 (no outgoing frame for stream 149 at any later time)
    11:02:00.578 received HEADERS frame for stream ID 151 with length 376 and flags END_HEADERS.
    11:02:00.581 sending HEADERS frame for stream ID 151 with length 34 and flags END_HEADERS.
                 ... full 430 KB response for 151 ...
    11:04:00.286 received RST_STREAM frame for stream ID 149 with length 4 and flags 0x0.        (client deadline)
    

    The client side (Private.InternalDiagnostics.System.Net.Http trace) confirms no frame for stream 149 arrived. No Kestrel warning or error was logged on the connection. There were no repeated SETTINGS frames: the connection saw only the initial SETTINGS exchange at 11:01:35, so the increasing-window SETTINGS from the original report are not a necessary condition.

    Pattern across our three occurrences (two on CI, one local): the lost stream was in every case the very next stream on the connection after a completed large response. Kestrel pools Http2Stream objects LIFO, so that next stream reuses the object of the stream that just completed.

    Possible mechanism, from reading release/10.0. Http2OutputProducer.StreamReset resets every scheduling field except _isScheduled. Http2FrameWriter.WriteToOutputPipe dequeues with while (_channel.Reader.TryRead(out var producer) && !producer.CompletedResponse), so a producer that was scheduled once more while its final write was in flight is dropped after CompleteResponseAsync without ever reaching ObserveDataAndState, which is the only place _isScheduled is cleared. A reused stream then inherits _isScheduled == true, and every Schedule() for the new stream returns early. That matches the trace exactly, including "only the stream right after a completed multi-window response". I could not pin down which Schedule() call races the final write; the late stream WINDOW_UPDATEs after the trailers are the obvious suspect. Resetting _isScheduled in StreamReset (or clearing it when the loop skips a completed producer) would make the reuse safe regardless of the race.

    I can share the full trace logs for the run if that helps.

  11. Misiu commented on Oct 2, 2026

    @Misiu

    TL;DR

    • We reproduce this on Kestrel 10.0.12 without gRPC or any third-party code: SocketsHttpHandler talks to Kestrel h2c on loopback.
    • About 1 in 6,000 responses is never sent. That happens when the previous response on the same pooled Http2Stream finished with its tail waiting on the client's stream window.
    • An instrumented run pins the cause. A WINDOW_UPDATE resume decides to schedule the producer while data is still pending, but enqueues it only after the response has completed. WriteToOutputPipe then drops that entry without clearing _isScheduled, and StreamReset does not clear it either. The next request on that pooled stream can never be scheduled.
    • Client-side workaround: start the client stream window at 16 MiB. It avoids the trigger for responses well below the window. It is not a fix.

    Why this matters to us

    We run a reverse proxy (YARP) that forwards requests over HTTP/2 to a Kestrel instance on the other side of a tunnel. One poisoned pooled stream means the next request on that connection gets no response at all, and Kestrel logs nothing. The proxy waits for its activity timeout (100 s by default) and then fails the request.

    With the default client window, any response larger than 64 KiB can poison a stream. In our load tests, plain YARP → Kestrel h2c hit the same hang. We would like to see this fixed in Kestrel, ideally serviced in 10.0. Our workaround only covers clients we control, and only responses smaller than the window.

    Root cause

    Proven (instrumented repro, numbers from our runs):

    1. Every hang starts with a stale flag.
      • 258 of 258 hung requests had Http2OutputProducer._isScheduled == true at handler start, before anything was written.
      • At the time of the hang they all still had _isScheduled == true and _streamWindow == 65535 (nothing sent), and no response HEADERS frame had been sent.
      • 258 of 260 requests that started with a stale flag hung.
    2. Clearing the flag removes the hangs.
      • Setting _isScheduled = false at handler start when it is found stale gives 0 hangs in 15 runs of 120,000 requests, although each run had 11–29 poisoned starts.
    3. Only reused stream objects are affected.
      • The stale flag was never on a freshly created Http2Stream (0 of 109); it was always on one reused from the stream pool.
      • In the Trace frame log, the previous user of the object ended with its final DATA + END_STREAM sent immediately after a WINDOW_UPDATE for that stream, in 109 of 109 cases. Only about 57% of all streams end that way.
    4. The extra entry always comes from the WINDOW_UPDATE path.
      • We wrapped the frame writer's _channel and recorded the call stack and producer state of every enqueue.
      • The frame writer drops an entry when CompletedResponse is already true. All 723 such dropped entries (2 runs) were enqueued from Http2Connection.ProcessWindowUpdateFrameAsync → Http2OutputProducer.TryUpdateStreamWindow → ScheduleResumeFromWindowUpdate → Schedule.
      • At enqueue time every one of them had _unconsumedBytes == 0 and _currentState already containing Completed.
      • 693 of the 723 (96%) already had _completedResponse == true.

    The interleaving this implies (consistent with the code on release/10.0):

    1. A response tail is waiting for stream window (_streamWindow <= 0, _unconsumedBytes > 0).
    2. A WINDOW_UPDATE arrives. Under _dataWriterLock, TryUpdateStreamWindow → UpdateStreamWindow decides to resume (wasDepleted && _streamWindow > 0 && _unconsumedBytes > 0) and releases the lock. ScheduleResumeFromWindowUpdate() runs afterwards, outside the lock.
    3. In between, WriteToOutputPipe writes the remaining bytes with END_STREAM. ObserveDataAndState clears _isScheduled, and usually CompleteResponseAsync sets _completedResponse.
    4. ScheduleResumeFromWindowUpdate then calls Schedule(). Its _completedResponse check is outside the lock and does not prevent this. _isScheduled goes back to true and the producer is enqueued again.
    5. WriteToOutputPipe dequeues that entry, sees CompletedResponse, and drops it (while (TryRead(out producer) && !producer.CompletedResponse)). ObserveDataAndState never runs for it, so _isScheduled stays true.
    6. Http2OutputProducer.StreamReset resets all scheduling state except _isScheduled. When the pooled Http2Stream serves the next request, every Schedule() returns early and nothing is ever written.

    Relation to earlier comments

    • This confirms @noocyte's reading of StreamReset and WriteToOutputPipe and identifies the Schedule() call that races the final write: the WINDOW_UPDATE resume.
    • One caveat on using the frame log as evidence: "WINDOW_UPDATE received after END_STREAM" appears on about 96% of all streams in our runs, so on its own it does not single out the poisoned streams. The enqueue probe does.
    • Not tested: a SETTINGS frame that changes SETTINGS_INITIAL_WINDOW_SIZE goes through the same TryUpdateOutputWindow → TryUpdateStreamWindow path for every open stream. That may explain the original report, where the client sent repeated SETTINGS with increasing window sizes.

    Workaround (client side)

    var handler = new SocketsHttpHandler
    {
        // dotnet/aspnetcore#53736: keep responses well below the stream window so their tail never waits on it.
        InitialHttp2StreamWindowSize = 16 * 1024 * 1024,
    };

    Why it works: the race needs a response tail blocked on the stream window, followed by a WINDOW_UPDATE resume. If the response fits comfortably in the initial window, no data waits on the window, so no resume is ever scheduled.

    Cost: 16 MiB is the default ceiling of SocketsHttpHandler's dynamic stream window (DOTNET_SYSTEM_NET_HTTP_SOCKETSHTTPHANDLER_FLOWCONTROL_MAXSTREAMWINDOWSIZE). The worst-case per-stream buffering is therefore unchanged; the window only starts at the ceiling instead of growing to it.

    Limits:

    • Responses close to or larger than the window are still exposed. With a static 256 KiB window and 256 KiB + 1 B responses we got 56 hangs in 300,000 requests.
    • It only helps HTTP/2 clients you control. Third-party clients of a public Kestrel endpoint are unaffected by it.
    • On the server, Http2Limits.InitialStreamWindowSize sets Kestrel's receive window (request bodies), so it does not help.
    • We found no server-side setting that avoids the bug.

    Minimal repro

    using System.Net;
    using Microsoft.AspNetCore.Hosting.Server;
    using Microsoft.AspNetCore.Hosting.Server.Features;
    using Microsoft.AspNetCore.Server.Kestrel.Core;
    
    var b = WebApplication.CreateBuilder();
    b.Logging.ClearProviders();
    b.WebHost.ConfigureKestrel(k => k.Listen(IPAddress.Loopback, 0, l => l.Protocols = HttpProtocols.Http2));
    var app = b.Build();
    app.MapPost("/echo", async (HttpContext ctx) =>
    {
        ctx.Response.ContentLength = ctx.Request.ContentLength;
        await ctx.Request.Body.CopyToAsync(ctx.Response.Body, ctx.RequestAborted);
    });
    await app.StartAsync();
    var url = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Single();
    
    // Workaround: new SocketsHttpHandler { InitialHttp2StreamWindowSize = 16 * 1024 * 1024 } -> hangs=0
    using var client = new HttpClient(new SocketsHttpHandler()) { BaseAddress = new Uri(url) };
    var payload = new byte[64 * 1024];
    var next = 0; var hangs = 0;
    await Task.WhenAll(Enumerable.Range(0, 16).Select(async _ =>
    {
        while (Interlocked.Increment(ref next) <= 120_000)
        {
            using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
            try
            {
                using var req = new HttpRequestMessage(HttpMethod.Post, "/echo")
                {
                    Content = new ByteArrayContent(payload),
                    Version = HttpVersion.Version20,
                    VersionPolicy = HttpVersionPolicy.RequestVersionExact,
                };
                using var resp = await client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cts.Token);
                await (await resp.Content.ReadAsStreamAsync(cts.Token)).CopyToAsync(Stream.Null, cts.Token);
            }
            catch (OperationCanceledException) { Interlocked.Increment(ref hangs); }
        }
    }));
    Console.WriteLine($"hangs={hangs}");
    • Expected: hangs=0.
    • Observed: hangs=20 (41 s), hangs=21 (41 s), hangs=28 (51 s) and hangs=14 (30 s) in four runs. With the workaround line applied: hangs=0. Each hang is a request that never receives response headers. Kestrel logs nothing.
    • A plain GET returning 64 KiB (no request body) also hangs, less often: 1 in 120,000 in one run.

    Full diagnostic repro

    The full program is in the collapsed section at the end. It is a single file for net10.0 (Microsoft.NET.Sdk.Web).

    Command Expected result
    dotnet run -c Release hangs > 0; for each hang it prints the producer state, e.g. _isScheduled at request start=True … _streamWindow=65535
    -- --window=16777216 hangs=0
    -- --simulate-fix hangs=0, while still reporting how many requests started with a stale flag
    -- --probe the call stacks and producer state behind every entry the frame writer dropped
    -- --trace Trace frame-log classification of how the previous user of each poisoned Http2Stream ended

    Response size vs. client stream window

    Echo workload, 16 concurrent requests, one connection. "Static" means System.Net.SocketsHttpHandler.Http2FlowControl.DisableDynamicWindowSizing = true.

    Client stream window Response Requests Hangs
    65,535 (default, dynamic) 64 KiB 10 × 120,000 195 (≈ 1 in 6,150)
    65,535 (default, dynamic) 65,535 B 10 × 120,000 7
    65,535 (default, dynamic) 32 KiB 10 × 120,000 0
    16 MiB 64 KiB 10 × 120,000 0 (95% upper bound 2.5 × 10⁻⁶ per request)
    16 MiB 1 MiB 3 × 40,000 0
    256 KiB, static 256 KiB + 1 B 5 × 60,000 56
    256 KiB, static 128 KiB 5 × 60,000 0

    Suggested fix (for the maintainers to judge)

    • Reset _isScheduled in Http2OutputProducer.StreamReset together with the other scheduling state, so a pooled stream never inherits it.
    • Make sure an entry that WriteToOutputPipe skips as CompletedResponse cannot leave _isScheduled set. For example: clear it when such an entry is skipped, or have the WINDOW_UPDATE resume re-check _unconsumedBytes / _completedResponse under _dataWriterLock before calling Schedule().

    Two caveats:

    • The skip loop exits the inner while when it meets a completed producer. That looks harmless today, but it is worth reviewing alongside this change.
    • Our --simulate-fix clears the flag at request start. That is only a diagnostic, not a proposed patch: 2 of 260 stale starts did not hang, which suggests that producer was still legitimately queued.

    Environment

    • Kestrel 10.0.12 (95017c711e6a), .NET runtime 10.0.12, SDK 10.0.401.
    • Windows 11 Pro 10.0.26200 x64, Intel Core Ultra 7 155H (22 logical CPUs), Server GC.
    • Loopback h2c, one HTTP/2 connection.
    Full diagnostic repro (single file, net10.0, Microsoft.NET.Sdk.Web)
    // Repro and diagnostics for dotnet/aspnetcore#53736: Kestrel HTTP/2 never sends a response because the
    // pooled Http2Stream starts a new request with Http2OutputProducer._isScheduled already true.
    // Kestrel h2c + SocketsHttpHandler over loopback, one connection, no other dependencies.
    //
    //   dotnet run -c Release                        64 KiB echo, default client stream window: expect hangs > 0
    //   dotnet run -c Release -- --window=16777216    same with a 16 MiB client stream window: expect hangs = 0
    //   dotnet run -c Release -- --simulate-fix       clears a stale _isScheduled at request start: expect hangs = 0
    //   dotnet run -c Release -- --probe              records who enqueues the producer entries that the frame
    //                                                writer later drops as already completed (slows Kestrel, so
    //                                                the race fires more often)
    //   dotnet run -c Release -- --trace              captures Kestrel's HTTP/2 frame log (Trace) and classifies
    //                                                how the previous user of a poisoned Http2Stream ended
    // Other options: --mode=echo|get|read-then-write --size=<bytes> --requests=N --concurrency=C --timeout=<s>
    //                --static-window (disable SocketsHttpHandler dynamic window sizing)
    //
    // Reads and writes Kestrel internals through reflection (Microsoft.AspNetCore.Server.Kestrel.Core 10.0).
    // Diagnostic only; field names may change between releases.
    using System.Collections.Concurrent;
    using System.Diagnostics;
    using System.Net;
    using System.Reflection;
    using Microsoft.AspNetCore.Hosting.Server;
    using Microsoft.AspNetCore.Hosting.Server.Features;
    using Microsoft.AspNetCore.Server.Kestrel.Core;
    
    string Arg(string name, string def) => args.FirstOrDefault(a => a.StartsWith($"--{name}="))?.Split('=', 2)[1] ?? def;
    var size = int.Parse(Arg("size", "65536"));
    var window = int.Parse(Arg("window", "65535"));
    var requests = int.Parse(Arg("requests", "120000"));
    var concurrency = int.Parse(Arg("concurrency", "16"));
    var timeout = TimeSpan.FromSeconds(int.Parse(Arg("timeout", "5")));
    var staticWindow = args.Contains("--static-window");
    var simulateFix = args.Contains("--simulate-fix");
    var trace = args.Contains("--trace");
    var probe = args.Contains("--probe");
    var mode = Arg("mode", "echo"); // echo: stream the request body back; get: no request body; read-then-write
    if (staticWindow)
        AppContext.SetSwitch("System.Net.SocketsHttpHandler.Http2FlowControl.DisableDynamicWindowSizing", true);
    
    const BindingFlags F = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
    static FieldInfo FieldOfType(Type t, string typeName)
    {
        for (var c = t; c != null; c = c.BaseType)
            foreach (var f in c.GetFields(F | BindingFlags.DeclaredOnly))
                if (f.FieldType.Name.StartsWith(typeName)) return f;
        throw new MissingFieldException(t.Name, typeName);
    }
    static object? Get(object o, string name)
    {
        for (var c = o.GetType(); c != null; c = c.BaseType)
            if (c.GetField(name, F | BindingFlags.DeclaredOnly) is { } f) return f.GetValue(o);
        throw new MissingFieldException(o.GetType().Name, name);
    }
    static void Set(object o, string name, object v)
    {
        for (var c = o.GetType(); c != null; c = c.BaseType)
            if (c.GetField(name, F | BindingFlags.DeclaredOnly) is { } f) { f.SetValue(o, v); return; }
    }
    
    var payload = new byte[size];
    new Random(1).NextBytes(payload);
    var previousStreamId = new System.Runtime.CompilerServices.ConditionalWeakTable<object, StrongBox<int>>();
    var staleOrigins = new ConcurrentQueue<(int StreamId, int PreviousStreamId)>();
    var byId = new ConcurrentDictionary<int, (object Stream, object Producer, int StreamId, bool StaleAtStart)>();
    long staleAtStart = 0, fixedAtStart = 0;
    
    var builder = WebApplication.CreateBuilder();
    builder.Logging.ClearProviders();
    var frameLog = new FrameLog();
    if (trace)
    {
        builder.Logging.SetMinimumLevel(LogLevel.None);
        builder.Logging.AddFilter("Microsoft.AspNetCore.Server.Kestrel.Http2", LogLevel.Trace);
        builder.Logging.AddProvider(frameLog);
    }
    builder.WebHost.ConfigureKestrel(k => k.Listen(IPAddress.Loopback, 0, l => l.Protocols = HttpProtocols.Http2));
    var app = builder.Build();
    app.MapMethods("/data/{id:int}", ["GET", "POST"], async (int id, HttpContext ctx) =>
    {
        var stream = ctx.Features; // for HTTP/2 this is Kestrel's (pooled) Http2Stream
        var producer = FieldOfType(stream.GetType(), "Http2OutputProducer").GetValue(stream)!;
        var streamId = (int)stream.GetType().GetProperty("StreamId", F)!.GetValue(stream)!;
        // Nothing has been written for this request yet, so the producer must not be scheduled.
        var stale = (bool)Get(producer, "_isScheduled")!;
        var box = previousStreamId.GetValue(stream, _ => new StrongBox<int>(0));
        if (stale) staleOrigins.Enqueue((streamId, box.Value));
        box.Value = streamId;
        if (stale)
        {
            Interlocked.Increment(ref staleAtStart);
            if (simulateFix) { Set(producer, "_isScheduled", false); Interlocked.Increment(ref fixedAtStart); }
        }
        byId[id] = (stream, producer, streamId, stale);
        if (probe) ChannelProbe.Install(producer);
        ctx.Response.ContentLength = payload.Length;
        if (mode == "echo")
        {
            await ctx.Request.Body.CopyToAsync(ctx.Response.Body, ctx.RequestAborted);
            return;
        }
        if (mode == "read-then-write")
            await ctx.Request.Body.CopyToAsync(Stream.Null, ctx.RequestAborted);
        await ctx.Response.Body.WriteAsync(payload, ctx.RequestAborted);
    });
    await app.StartAsync();
    var url = app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.Single();
    
    using var client = new HttpClient(new SocketsHttpHandler { InitialHttp2StreamWindowSize = window })
    {
        BaseAddress = new Uri(url),
        DefaultRequestVersion = HttpVersion.Version20,
        DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact,
    };
    Console.WriteLine($"Kestrel {FileVersionInfo.GetVersionInfo(typeof(KestrelServerOptions).Assembly.Location).ProductVersion}, " +
                      $"runtime {Environment.Version}, {System.Runtime.InteropServices.RuntimeInformation.OSDescription}, {Environment.ProcessorCount} CPUs; " +
                      $"mode={mode}, body={size} B, client initial stream window={window} B, dynamic window={(staticWindow ? "off" : "on")}, " +
                      $"requests={requests}, concurrency={concurrency}, simulate-fix={simulateFix}");
    
    var next = 0; var hangs = 0; var hangsStale = 0; var sw = Stopwatch.StartNew();
    await Task.WhenAll(Enumerable.Range(0, concurrency).Select(async _ =>
    {
        var buf = new byte[64 * 1024];
        int id;
        while ((id = Interlocked.Increment(ref next)) <= requests)
        {
            using var cts = new CancellationTokenSource(timeout);
            var gotHeaders = false;
            try
            {
                using var request = new HttpRequestMessage(mode == "get" ? HttpMethod.Get : HttpMethod.Post, $"/data/{id}") { Version = HttpVersion.Version20, VersionPolicy = HttpVersionPolicy.RequestVersionExact };
                if (mode != "get") request.Content = new ByteArrayContent(payload);
                using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cts.Token);
                gotHeaders = true;
                await using var body = await response.Content.ReadAsStreamAsync(cts.Token);
                while (await body.ReadAsync(buf, cts.Token) > 0) { }
            }
            catch (OperationCanceledException)
            {
                Interlocked.Increment(ref hangs);
                if (byId.TryGetValue(id, out var s))
                {
                    if (s.StaleAtStart) Interlocked.Increment(ref hangsStale);
                    Console.WriteLine(
                        $"  HANG request {id}: response headers received={gotHeaders}, Kestrel stream {s.StreamId}, " +
                        $"_isScheduled at request start={s.StaleAtStart}, now: _isScheduled={Get(s.Producer, "_isScheduled")}, " +
                        $"_streamWindow={Get(s.Producer, "_streamWindow")}, _completedResponse={Get(s.Producer, "_completedResponse")}");
                }
                else Console.WriteLine($"  HANG request {id}: request never reached the server handler");
            }
            finally { byId.TryRemove(id, out var _); }
        }
    }));
    if (trace)
    {
        var late = frameLog.StreamsWithWindowUpdateAfterEndStream();
        var origins = staleOrigins.ToArray();
        var withLate = origins.Count(o => late.Contains(o.PreviousStreamId));
        Console.WriteLine($"TRACE streams that received a WINDOW_UPDATE after sending END_STREAM: {late.Count} of {frameLog.StreamCount} " +
                          $"({100.0 * late.Count / Math.Max(1, frameLog.StreamCount):F2}%)");
        Console.WriteLine($"TRACE stale-start streams whose pooled object previously served such a stream: {withLate} of {origins.Length}");
        var fromWindow = frameLog.StreamsCompletedFromWindowUpdate();
        Console.WriteLine($"TRACE streams whose END_STREAM was sent right after a WINDOW_UPDATE (tail blocked on window): {fromWindow.Count} of {frameLog.StreamCount} " +
                          $"({100.0 * fromWindow.Count / Math.Max(1, frameLog.StreamCount):F2}%)");
        Console.WriteLine($"TRACE stale-start streams whose pooled object previously served such a stream: {origins.Count(o => fromWindow.Contains(o.PreviousStreamId))} of {origins.Length}");
        Console.WriteLine($"TRACE stale-start streams on a never-before-used Http2Stream object: {origins.Count(o => o.PreviousStreamId == 0)}");
        foreach (var (streamId, previous) in origins.Take(1))
        {
            Console.WriteLine($"  Example: stream {streamId} started with stale _isScheduled; its Http2Stream object last served stream {previous}:");
            foreach (var line in frameLog.For(previous).Concat(frameLog.For(streamId).Take(3)))
                Console.WriteLine("    " + line);
        }
    }
    if (probe) ChannelProbe.Report();
    Console.WriteLine($"RESULT hangs={hangs} (of which stale _isScheduled at request start={hangsStale}); " +
                      $"requests that started with stale _isScheduled={staleAtStart}, cleared by simulated fix={fixedAtStart}; elapsed={sw.Elapsed.TotalSeconds:F0}s");
    
    
    sealed class StrongBox<T>(T value) { public T Value = value; }
    
    sealed class FrameLog : ILoggerProvider, ILogger
    {
        private readonly ConcurrentQueue<(long Ticks, string Message)> _lines = new();
        private static readonly System.Text.RegularExpressions.Regex s_stream = new(@"stream ID (\d+)");
        public ILogger CreateLogger(string categoryName) => this;
        public void Dispose() { }
        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)
            => _lines.Enqueue((Stopwatch.GetTimestamp(), formatter(state, exception)));
        public int StreamCount => _lines.Select(l => s_stream.Match(l.Message)).Where(m => m.Success).Select(m => m.Groups[1].Value).Distinct().Count();
    
        // Streams whose END_STREAM was sent immediately after a WINDOW_UPDATE for that stream arrived,
        // i.e. the tail of the response had been blocked on the stream window.
        public HashSet<int> StreamsCompletedFromWindowUpdate()
        {
            var lastEvent = new Dictionary<int, string>();
            var result = new HashSet<int>();
            foreach (var (_, message) in _lines)
            {
                var m = s_stream.Match(message);
                if (!m.Success) continue;
                var id = int.Parse(m.Groups[1].Value);
                if (message.Contains("sending") && message.Contains("END_STREAM") &&
                    lastEvent.TryGetValue(id, out var previous) && previous.Contains("received WINDOW_UPDATE"))
                    result.Add(id);
                lastEvent[id] = message;
            }
            return result;
        }
    
        public HashSet<int> StreamsWithWindowUpdateAfterEndStream()
        {
            var ended = new HashSet<int>();
            var late = new HashSet<int>();
            foreach (var (_, message) in _lines)
            {
                var m = s_stream.Match(message);
                if (!m.Success) continue;
                var id = int.Parse(m.Groups[1].Value);
                if (message.Contains("sending") && message.Contains("END_STREAM")) ended.Add(id);
                else if (message.Contains("received WINDOW_UPDATE") && ended.Contains(id)) late.Add(id);
            }
            return late;
        }
    
        public IEnumerable<string> For(int streamId)
        {
            var start = _lines.FirstOrDefault().Ticks;
            foreach (var (ticks, message) in _lines)
            {
                var m = s_stream.Match(message);
                if (m.Success && int.Parse(m.Groups[1].Value) == streamId)
                    yield return $"{(ticks - start) * 1000.0 / Stopwatch.Frequency,10:F3} ms  {message[(message.IndexOf('"', message.IndexOf('"') + 1) + 2)..]}";
            }
        }
    }
    
    
    static class ChannelProbe
    {
        private static int s_installed;
        public static readonly ConcurrentDictionary<string, int> Drops = new();
        public static long Writes, Reads;
    
        public static void Install(object producer)
        {
            if (Interlocked.Exchange(ref s_installed, 1) == 1) return;
            var frameWriter = producer.GetType().GetField("_frameWriter", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(producer)!;
            var field = frameWriter.GetType().GetField("_channel", BindingFlags.Instance | BindingFlags.NonPublic)!;
            var inner = field.GetValue(frameWriter)!;
            var wrapperType = typeof(ProbeChannel<>).MakeGenericType(producer.GetType());
            field.SetValue(frameWriter, Activator.CreateInstance(wrapperType, inner));
            Console.WriteLine("PROBE installed on the frame writer channel");
        }
    
        public static void Report()
        {
            Console.WriteLine($"PROBE enqueues={Writes}, dequeues={Reads}, entries dropped because the producer had already completed: {Drops.Values.Sum()}");
            static string Normalize(string s) => System.Text.RegularExpressions.Regex.Replace(
                s.Replace("Http2FrameWriter.Schedule" + Environment.NewLine, "").Replace("      Http2OutputProducer.Schedule" + Environment.NewLine, ""),
                @"_streamWindow=-?\d+", "_streamWindow=*");
            foreach (var group in Drops.GroupBy(kv => Normalize(kv.Key)).OrderByDescending(g => g.Sum(kv => kv.Value)))
                Console.WriteLine($"PROBE   {group.Sum(kv => kv.Value)} x enqueued by:{Environment.NewLine}{group.Key}");
        }
    }
    
    sealed class ProbeChannel<T> : System.Threading.Channels.Channel<T> where T : class
    {
        private static readonly FieldInfo s_completed = typeof(T).GetField("_completedResponse", BindingFlags.Instance | BindingFlags.NonPublic)!;
        private static readonly FieldInfo s_lock = typeof(T).GetField("_dataWriterLock", BindingFlags.Instance | BindingFlags.NonPublic)!;
        private static readonly FieldInfo s_unconsumed = typeof(T).GetField("_unconsumedBytes", BindingFlags.Instance | BindingFlags.NonPublic)!;
        private static readonly FieldInfo s_window = typeof(T).GetField("_streamWindow", BindingFlags.Instance | BindingFlags.NonPublic)!;
        private static readonly FieldInfo s_current = typeof(T).GetField("_currentState", BindingFlags.Instance | BindingFlags.NonPublic)!;
        private readonly ConcurrentDictionary<T, ConcurrentQueue<string>> _origins = new(ReferenceEqualityComparer.Instance);
    
        public ProbeChannel(System.Threading.Channels.Channel<T> inner)
        {
            Reader = new ProbeReader(inner.Reader, this);
            Writer = new ProbeWriter(inner.Writer, this);
        }
    
        private static string Origin()
        {
            var frames = new StackTrace(2, false).GetFrames()
                .Select(f => f.GetMethod())
                .Where(m => m != null && m.DeclaringType != null && !m.DeclaringType.FullName!.StartsWith("System.Runtime.CompilerServices") && !m.DeclaringType.FullName!.StartsWith("System.Threading"))
                .Take(6)
                .Select(m => $"      {m!.DeclaringType!.Name}.{m.Name}");
            return string.Join(Environment.NewLine, frames);
        }
    
        private sealed class ProbeWriter(System.Threading.Channels.ChannelWriter<T> inner, ProbeChannel<T> owner) : System.Threading.Channels.ChannelWriter<T>
        {
            public override bool TryWrite(T item)
            {
                string snapshot;
                lock (s_lock.GetValue(item)!)
                    snapshot = $"      [state at enqueue: _unconsumedBytes={s_unconsumed.GetValue(item)}, _streamWindow={s_window.GetValue(item)}, " +
                               $"_currentState={s_current.GetValue(item)}, _completedResponse={s_completed.GetValue(item)}]";
                owner._origins.GetOrAdd(item, _ => new ConcurrentQueue<string>()).Enqueue(Origin() + Environment.NewLine + snapshot);
                Interlocked.Increment(ref ChannelProbe.Writes);
                return inner.TryWrite(item);
            }
            public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken = default) => inner.WaitToWriteAsync(cancellationToken);
            public override bool TryComplete(Exception? error = null) => inner.TryComplete(error);
        }
    
        private sealed class ProbeReader(System.Threading.Channels.ChannelReader<T> inner, ProbeChannel<T> owner) : System.Threading.Channels.ChannelReader<T>
        {
            public override bool TryRead(out T item)
            {
                if (!inner.TryRead(out item!)) return false;
                Interlocked.Increment(ref ChannelProbe.Reads);
                owner._origins.TryGetValue(item, out var q);
                string? origin = null;
                q?.TryDequeue(out origin);
                bool completed;
                lock (s_lock.GetValue(item)!) completed = (bool)s_completed.GetValue(item)!;
                if (completed) ChannelProbe.Drops.AddOrUpdate(origin ?? "(unknown)", 1, (_, c) => c + 1);
                return true;
            }
            public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken = default) => inner.WaitToReadAsync(cancellationToken);
            public override Task Completion => inner.Completion;
        }
    }
  12. Misiu commented on Oct 12, 2026

    @Misiu

    PR #69690 resolves this issue for us. We've verified the fix against .NET 10.0.12, with the test results documented in the PR.

    Could someone from the Kestrel team take a look at the PR and advise on the next steps toward getting it reviewed and merged? We'd also appreciate knowing whether the fix could be considered for an upcoming .NET 10 servicing release.

    Thanks for your help!

  13. elafarge commented on Oct 16, 2026

    @elafarge

    Just chiming in to say that we've been experiencing the issue as well and would love the patch PR to be merged :)

    In case that's useful to anyone until the script is merged and released, we've came up with a slightly different workaround, we're using a gRPC middleware to check - via reflexion (only used at startup time) - if the Http2OutputProducer as _isScheduled set to true and set it back to false when a stream is opened.

    It's gRPC specific but I think a similar "generic" HTTP middleware could be implemented.

    One important note if you wish to implement something similar: ensure that there's no reflexion (and ideally no allocation, boxing, etc.) involved in the middleware as it could have a significant performance penalty for EVERY HTTP/2 request.

    The reflexion based accessor & patch method for Http2OutputProducer

    using System;
    using System.Linq.Expressions;
    using System.Reflection;
    using System.Threading;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Server.Kestrel.Core;
    using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
    using ServiceUtils.Exceptions;
    
    namespace ServiceUtils.Network;
    
    /// <summary>
    /// Access to the private scheduling state of Kestrel's <c>Http2OutputProducer</c>.
    /// Only used by <see cref="KestrelHttp2StaleScheduleRepair"/>; see the TODO there for when to delete this.
    ///
    /// Reflection is only used once, at type initialisation, to find the fields and validate their names and
    /// types against the Kestrel version we rely on. The fields are then compiled into plain delegates, so the
    /// per-request path is direct field access: no reflection call, no boxing. If anything does not match
    /// (a Kestrel servicing update renamed a field), the accessor reports itself unavailable and nothing is
    /// touched at runtime.
    /// </summary>
    internal sealed class KestrelHttp2OutputProducerAccessor
    {
        private const string Http2StreamTypeName = "Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2Stream";
        private const string Http2OutputProducerTypeName = "Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http2.Http2OutputProducer";
        private const BindingFlags PrivateInstance = BindingFlags.Instance | BindingFlags.NonPublic;
    
        public static KestrelHttp2OutputProducerAccessor Instance { get; } = Create();
    
        private readonly Type _http2StreamType;
        private readonly Func<object, object?> _getHttp2Output;
        private readonly Func<object, Lock> _getDataWriterLock;
        private readonly Func<object, bool> _getIsScheduled;
        private readonly Action<object, bool> _setIsScheduled;
        private readonly Func<object, bool> _getCompleteScheduled;
        private readonly Func<object, long> _getUnconsumedBytes;
        private readonly Func<object, int> _getUnobservedState;
    
        /// <summary>
        /// Null when the Kestrel internals look exactly like we expect; otherwise a human-readable reason.
        /// </summary>
        public string? UnavailableReason { get; }
    
        public bool IsAvailable => UnavailableReason is null;
    
        /// <summary>
        /// Clears a stale <c>_isScheduled</c> flag on the current request's pooled <c>Http2OutputProducer</c>.
        /// Must be called before anything has been written to the response.
        /// </summary>
        /// <returns>true if a stale flag was found and cleared.</returns>
        public bool TryRepairStaleScheduledFlag(HttpContext context)
        {
            if (!IsAvailable || !TryGetOutputProducer(context, out var producer))
                return false;
    
            // Same lock Http2OutputProducer.Schedule() and ObserveDataAndState() take, so we can never
            // race with the frame writer or a window update on this producer.
            lock (_getDataWriterLock(producer))
            {
                if (!_getIsScheduled(producer))
                    return false;
    
                // Nothing has been written for this request yet, so the only legitimate way for the producer
                // to be scheduled is an abort (Stop() sets _completeScheduled). Anything else is a flag that
                // leaked from the previous request on this pooled stream: the frame writer has no queue entry
                // for it, and every Schedule() of this request would return early. Only touch pristine producers.
                if (_getCompleteScheduled(producer) || _getUnconsumedBytes(producer) != 0 || _getUnobservedState(producer) != 0)
                    return false;
    
                _setIsScheduled(producer, false);
                return true;
            }
        }
    
        /// <summary>
        /// Kestrel's Http2Stream is the request's feature collection and implements <see cref="IHttp2StreamIdFeature"/>
        /// itself, which is the cheapest robust way to get hold of it from an HttpContext.
        /// </summary>
        internal bool TryGetOutputProducer(HttpContext context, out object producer)
        {
            producer = null!;
            if (!IsAvailable)
                return false;
    
            var stream = context.Features.Get<IHttp2StreamIdFeature>();
            if (stream is null || !_http2StreamType.IsInstanceOfType(stream))
                return false;
    
            var value = _getHttp2Output(stream);
            if (value is null)
                return false;
    
            producer = value;
            return true;
        }
    
        private KestrelHttp2OutputProducerAccessor(string unavailableReason)
        {
            UnavailableReason = unavailableReason;
            _http2StreamType = null!;
            _getHttp2Output = null!;
            _getDataWriterLock = null!;
            _getIsScheduled = null!;
            _setIsScheduled = null!;
            _getCompleteScheduled = null!;
            _getUnconsumedBytes = null!;
            _getUnobservedState = null!;
        }
    
        private KestrelHttp2OutputProducerAccessor(
            Type http2StreamType,
            Func<object, object?> getHttp2Output,
            Func<object, Lock> getDataWriterLock,
            Func<object, bool> getIsScheduled,
            Action<object, bool> setIsScheduled,
            Func<object, bool> getCompleteScheduled,
            Func<object, long> getUnconsumedBytes,
            Func<object, int> getUnobservedState)
        {
            _http2StreamType = http2StreamType;
            _getHttp2Output = getHttp2Output;
            _getDataWriterLock = getDataWriterLock;
            _getIsScheduled = getIsScheduled;
            _setIsScheduled = setIsScheduled;
            _getCompleteScheduled = getCompleteScheduled;
            _getUnconsumedBytes = getUnconsumedBytes;
            _getUnobservedState = getUnobservedState;
        }
    
        private static KestrelHttp2OutputProducerAccessor Create()
        {
            try
            {
                var kestrelAssembly = typeof(KestrelServerOptions).Assembly;
    
                var http2StreamType = kestrelAssembly.GetType(Http2StreamTypeName)
                    ?? throw new MissingMemberException($"Type {Http2StreamTypeName} not found in {kestrelAssembly.GetName().Name}");
                if (!typeof(IHttp2StreamIdFeature).IsAssignableFrom(http2StreamType))
                    throw new MissingMemberException($"{Http2StreamTypeName} no longer implements {nameof(IHttp2StreamIdFeature)}");
    
                var http2OutputField = GetField(http2StreamType, "_http2Output");
                var producerType = http2OutputField.FieldType;
                if (producerType.FullName != Http2OutputProducerTypeName)
                    throw new MissingMemberException($"{Http2StreamTypeName}._http2Output is a {producerType.FullName}, expected {Http2OutputProducerTypeName}");
    
                var isScheduledField = GetField(producerType, "_isScheduled", typeof(bool));
                var completeScheduledField = GetField(producerType, "_completeScheduled", typeof(bool));
                var unconsumedBytesField = GetField(producerType, "_unconsumedBytes", typeof(long));
                var unobservedStateField = GetField(producerType, "_unobservedState");
                if (!unobservedStateField.FieldType.IsEnum)
                    throw new MissingMemberException($"{Http2OutputProducerTypeName}._unobservedState is not an enum");
                var dataWriterLockField = GetField(producerType, "_dataWriterLock", typeof(Lock));
    
                return new KestrelHttp2OutputProducerAccessor(
                    http2StreamType,
                    CompileGetter<object?>(http2OutputField),
                    CompileGetter<Lock>(dataWriterLockField),
                    CompileGetter<bool>(isScheduledField),
                    CompileSetter<bool>(isScheduledField),
                    CompileGetter<bool>(completeScheduledField),
                    CompileGetter<long>(unconsumedBytesField),
                    CompileGetter<int>(unobservedStateField));
            }
            catch (Exception e) when (ExceptionMatcher.IsRecoverable(e))
            {
                return new KestrelHttp2OutputProducerAccessor($"{e.GetType().Name}: {e.Message} (Kestrel {typeof(KestrelServerOptions).Assembly.GetName().Version})");
            }
        }
    
        private static FieldInfo GetField(Type type, string name, Type? expectedType = null)
        {
            var field = type.GetField(name, PrivateInstance)
                ?? throw new MissingFieldException($"Field {type.FullName}.{name} not found");
            if (expectedType is not null && field.FieldType != expectedType)
                throw new MissingFieldException($"Field {type.FullName}.{name} is a {field.FieldType.FullName}, expected {expectedType.FullName}");
            return field;
        }
    
        /// <summary>
        /// <c>(object instance) => (T)((DeclaringType)instance).field</c>. Compiled expression trees may read private
        /// fields, and the result is a direct field load.
        /// </summary>
        private static Func<object, T> CompileGetter<T>(FieldInfo field)
        {
            var instance = Expression.Parameter(typeof(object), "instance");
            var access = Expression.Field(Expression.Convert(instance, field.DeclaringType!), field);
            return Expression.Lambda<Func<object, T>>(Expression.Convert(access, typeof(T)), instance).Compile();
        }
    
        /// <summary>
        /// <c>(object instance, T value) => ((DeclaringType)instance).field = value</c>.
        /// </summary>
        private static Action<object, T> CompileSetter<T>(FieldInfo field)
        {
            var instance = Expression.Parameter(typeof(object), "instance");
            var value = Expression.Parameter(typeof(T), "value");
            var access = Expression.Field(Expression.Convert(instance, field.DeclaringType!), field);
            return Expression.Lambda<Action<object, T>>(Expression.Assign(access, value), instance, value).Compile();
        }
    }

    And the gRPC middleware:

    using System;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.DependencyInjection.Extensions;
    using Microsoft.Extensions.Logging;
    
    namespace ServiceUtils.Network;
    
    /// <summary>
    /// Workaround for a Kestrel HTTP/2 bug that silently drops a whole response (headers, data, trailers)
    /// while the application sees the request complete normally: https://github.com/dotnet/aspnetcore/issues/53736
    ///
    /// TODO(remove-workaround): delete this class, <see cref="KestrelHttp2OutputProducerAccessor"/>, their tests
    /// and the registration in GrpcServiceExtensions once https://github.com/dotnet/aspnetcore/pull/69690 (or an
    /// equivalent fix) is merged, shipped in a .NET servicing release, AND our `mcr.microsoft.com/dotnet/aspnet:10.0`
    /// images actually run that version. No more "Repaired stale Kestrel HTTP/2 output scheduling flag" warnings
    /// after that upgrade is the confirmation; until then that warning is also our only detector for the bug.
    ///
    /// Mechanism (Kestrel release/10.0, verified on 10.0.12): a stream WINDOW_UPDATE that arrives while the
    /// tail of a response is waiting for stream window races the frame writer finishing that response. The
    /// late Schedule() re-queues the already completed Http2OutputProducer; the frame writer drops that entry
    /// without clearing `_isScheduled`, and `StreamReset()` does not clear it either. Kestrel pools
    /// Http2Stream objects, so the next request served by that object inherits `_isScheduled == true`,
    /// every Schedule() for it returns early, and nothing is ever written to the wire. The client waits
    /// until its own timeout, Kestrel logs nothing, and other streams on the connection keep working.
    ///
    /// In our mesh the client is the Envoy sidecar: the poisoned stream only ends when the pod dies
    /// (Kestrel's graceful shutdown waits for it, hence "non graceful shutdown" alerts), Envoy then
    /// reports `UC` / gRPC 14 and retries elsewhere, minutes to hours later.
    ///
    /// This startup filter inserts a middleware at the very front of the pipeline that clears the stale
    /// flag before anything is written for the request. At that point a scheduled producer can only mean
    /// "aborted" (guarded against) or "stale", so the repair is safe; in the worst case the frame writer
    /// observes the producer twice, which is a no-op.
    /// </summary>
    public static class KestrelHttp2StaleScheduleRepair
    {
        /// <summary>
        /// Set to "false" to disable the workaround without a code change. Defaults to enabled.
        /// </summary>
        public const string EnabledEnvironmentVariable = "KESTREL_HTTP2_STALE_SCHEDULE_REPAIR_ENABLED";
    
        /// <summary>
        /// Registers the workaround. Called from <see cref="GrpcServiceExtensions.ConfigureGrpcServer"/>, as the bug
        /// only affects HTTP/2 and our only HTTP/2 listener is the gRPC port. Idempotent.
        /// </summary>
        public static IServiceCollection AddKestrelHttp2StaleScheduleRepair(this IServiceCollection services)
        {
            if (!IsEnabledByEnvironment())
                return services;
    
            services.TryAddEnumerable(ServiceDescriptor.Transient<IStartupFilter, StartupFilter>());
            return services;
        }
    
        internal static bool IsEnabledByEnvironment()
        {
            var value = Environment.GetEnvironmentVariable(EnabledEnvironmentVariable);
            return !bool.TryParse(value, out var enabled) || enabled;
        }
    
        private sealed class StartupFilter : IStartupFilter
        {
            public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
            {
                return app =>
                {
                    var logger = app.ApplicationServices.GetRequiredService<ILoggerFactory>().CreateLogger(typeof(KestrelHttp2StaleScheduleRepair));
                    var accessor = KestrelHttp2OutputProducerAccessor.Instance;
    
                    if (accessor.IsAvailable)
                    {
                        logger.LogInformation("Kestrel HTTP/2 stale schedule repair is active (dotnet/aspnetcore#53736)");
                        app.Use((context, nextMiddleware) =>
                        {
                            if (HttpProtocol.IsHttp2(context.Request.Protocol) && accessor.TryRepairStaleScheduledFlag(context))
                            {
                                // Deliberately a log and not a metric: it fires a few times a day fleet-wide, and we want the path.
                                var request = context.Request;
                                logger.LogWarning(
                                    "Repaired stale Kestrel HTTP/2 output scheduling flag on stream {StreamId} for {Method} {Path}; without it the response would never have been sent (dotnet/aspnetcore#53736)",
                                    context.Features.Get<IHttp2StreamIdFeature>()?.StreamId,
                                    request.Method,
                                    request.Path.Value);
                            }
    
                            return nextMiddleware(context);
                        });
                    }
                    else
                    {
                        // Expected after a Kestrel update that changes its internals: the workaround then has to be
                        // re-validated (or deleted, see the TODO above). Alerted on in Datadog.
                        logger.LogWarning("Kestrel HTTP/2 stale schedule repair is DISABLED, Kestrel internals do not match: {Reason}", accessor.UnavailableReason);
                    }
    
                    next(app);
                };
            }
        }
    }
  14. locked and limited conversation to collaborators on Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-grpcarea-networking

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions