Skip to content

Fix HTTP/2 hang on reused streams when a window update races the final write - #69690

Merged
halter73 merged 2 commits into
dotnet:mainfrom
danield137:fix/http2-stream-reuse-stale-schedule
Oct 29, 2026
Merged

halter73 merged 2 commits into
dotnet:mainfrom
danield137:fix/http2-stream-reuse-stale-schedule

Conversation

@danield137

Copy link
Copy Markdown
Contributor

Fix HTTP/2 hang on reused streams when a window update races the final write

  • You've read the Contributor Guide and Code of Conduct.
  • You've included unit or integration tests for your change, where applicable.
  • You've included inline docs for your change, where applicable.
  • There's an open issue for the PR that you are making.

Unschedule completed HTTP/2 producers so pooled streams can be reused

Description

Kestrel can reuse a pooled Http2Stream whose Http2OutputProducer still has _isScheduled set but has no entry in Http2FrameWriter's queue. Every Schedule() for the new request then returns early, so its HEADERS, DATA, and trailers are never written and its aborts are never processed. The client waits until its own timeout, nothing is logged, and other streams on the connection keep working. If the handler writes more than the stream's 4 KB output buffer, its write never completes. On connection close, Http2Connection then waits for that stream indefinitely.

How the flag gets stuck

  1. A stream WINDOW_UPDATE arrives while the response's tail is waiting on the stream window. TryUpdateStreamWindow decides to resume while holding _dataWriterLock, then calls ScheduleResumeFromWindowUpdate() -> Schedule() after releasing it.
  2. In between, the frame writer sees the new window and writes the tail. ObserveDataAndState() clears _isScheduled.
  3. The late Schedule() sets _isScheduled again and queues the producer a second time. The _completedResponse check in ScheduleResumeFromWindowUpdate isn't taken under the lock.
  4. The writer completes the response, and the connection pools the stream.
  5. The writer dequeues the extra entry. while (TryRead(out producer) && !producer.CompletedResponse) drops it without clearing _isScheduled.
  6. StreamReset() doesn't reset _isScheduled, so the request that reuses the stream can never be scheduled.

Fix

Http2FrameWriter.WriteToOutputPipe now calls the new Http2OutputProducer.TryUnscheduleCompletedResponse() for each dequeued producer. If the response has already completed, that method clears _isScheduled and the writer skips the producer and continues with the next one. The check and the clear happen under _dataWriterLock, the same lock Schedule() uses, so a producer can't end up both unqueued and marked scheduled. The cost is unchanged, because the old loop condition took the same lock through the CompletedResponse getter.

Alternatives considered (evaluated against the new tests):

  • Make Schedule() return early once _completedResponse is set: this only covers a schedule that lands after completion. The "during final write" ordering still hangs.
  • Clear _isScheduled in StreamReset(): this hides the symptom at reuse, but it leaves the skip path inconsistent. If the extra entry is still queued when the stream is reset, it also allows a second queue entry for the same producer.
  • Don't pool a stream whose producer is still scheduled: this avoids the hang by discarding the stream, but leaves the flag stuck.

Tests

New tests in Http2ConnectionTests (InMemory.FunctionalTests):

  • StreamPool_ScheduledAfterResponseCompleted_PooledStreamReusedAndResponseSent(largeResponse: false|true): the producer is scheduled after its response completed, then the stream is pooled and reused for a response with headers, data, and trailers. The small response is buffered so the app completes without waiting on output. The large one (32 KB) awaits its writes.
  • StreamPool_ScheduledDuringFinalWrite_PooledStreamReusedAndResponseSent: the first response's final write is held at its flush, so ScheduleResumeFromWindowUpdate() lands after ObserveDataAndState() and before CompleteResponseAsync(). The test then lets the writer complete the response and dequeue the extra entry, and reuses the stream.

Without the product change, all three cases time out waiting for the reused stream's HEADERS (5 of 5 runs). With it, they pass (20 of 20 runs).

Other validation on Windows x64 against main (16e71d2):

  • Microsoft.AspNetCore.Server.Kestrel.Core.Tests: 9913 passed, 1 skipped.
  • InMemory.FunctionalTests: 1661 passed, 5 skipped, 1 failed. The failure, HttpsConnectionMiddlewareTests.HandshakeExceptionIsAvailableAfterHandshakeFailure, also fails without this change on the same machine.
  • Interop.FunctionalTests HTTP/2 and h2spec subset: 376 passed, 1 skipped, including all 292 h2spec cases.
  • Natural race, no fault injection, using the 64 KiB echo workload from Kestrel occasionally losing zero-size GRPC responses #53736 (16 concurrent requests on one h2c connection, default SocketsHttpHandler, Release builds): unpatched, 24 of 240,000 requests never got response headers (2 runs of 120,000); patched, 0 of 360,000 (3 runs).

Servicing

This regressed in 7.0 with #40925; the original report on #53736 notes it started after moving from 6.0. The same code is in release/8.0, release/9.0, release/10.0, and release/11.0, and this patch applies to each. I'd suggest backporting it to 10.0 and 8.0, plus 9.0 and 11.0 per the servicing policy.

  • Customer impact: intermittent HTTP/2 requests (often gRPC) that never get a response and are never cleaned up. Any response larger than the client's stream window can leave the next stream on the connection unusable. The only mitigation is client-side (a larger initial stream window).
  • Risk: low. The change only affects a producer whose response has already completed, in the loop that already skipped those producers, and it uses the same lock as before.

Thanks to @noocyte and @Misiu for the analysis and repro in #53736.

Fixes #53736

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 <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 7, 2026 04:04
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Oct 7, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Thanks for your PR, @danield137. Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@github-actions github-actions Bot added the area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions label Oct 7, 2026
@danield137

Copy link
Copy Markdown
Contributor Author

@dotnet-policy-service agree company="Microsoft"

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🔵 Needs a closer look

The concurrency-sensitive stream-reuse change needs final human review because independent verification was unavailable.

Review effort: Balanced
Findings: None

What changed in this PR

Addresses #53736 by preventing stale scheduling state from blocking responses on reused Kestrel HTTP/2 streams.

Changes:

  • Clears completed producers’ scheduling state under the existing lock and continues draining the writer queue.
  • Adds regression tests for scheduling during and after response completion, including small and large responses.
File Description
src/​Servers/​Kestrel/​test/​InMemory.FunctionalTests/​Http2/​Http2ConnectionTests.cs Tests pooled-stream reuse after late scheduling.
src/​Servers/​Kestrel/​Core/​src/​Internal/​Http2/​Http2OutputProducer.cs Adds atomic unscheduling for completed responses.
src/​Servers/​Kestrel/​Core/​src/​Internal/​Http2/​Http2FrameWriter.cs Unschedules completed producers before skipping them.

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

@Misiu

Misiu commented Oct 8, 2026

Copy link
Copy Markdown

We built Kestrel.Core from the .NET 10.0.12 sources with and without this patch and tested both using isolated runtime copies on Windows x64 (Release).

The HTTP/2 echo test used 64 KiB payloads and one reused h2c connection, without the 16 MiB window workaround.

Concurrent requests Requests per variant Unpatched hangs Patched hangs
16 360,000 61 0
32 1,000,000 84 0
64 1,000,000 33 0
Total 2,360,000 178 0

All completed responses were verified byte-for-byte. No timeouts or payload mismatches occurred with the patch. Our relay test suite also passed: 131/131 tests.

We confirm that this fix resolves the hang in our reproduction. Thanks for the fix!

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime.
To make sure no conflicting changes have occurred, please rerun validation before merging. You can do this by leaving an /azp run comment here (requires commit rights), or by simply closing and reopening.

@dotnet-policy-service dotnet-policy-service Bot added the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Oct 15, 2026
@Misiu

Misiu commented Oct 15, 2026

Copy link
Copy Markdown

PR is waiting for review.

@magiino

magiino commented Oct 23, 2026

Copy link
Copy Markdown

We are experiencing the same issue on our side. Looking forward to a fix. Thanks for looking into it! 🚀

@azure-pipelines

Copy link
Copy Markdown
Commenter does not have sufficient privileges for PR 69690 in repo dotnet/aspnetcore

@halter73 halter73 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the thorough investigation and well thought-out fix!

@halter73
halter73 merged commit 169d6d2 into dotnet:main Oct 29, 2026
30 checks passed
@halter73
halter73 temporarily deployed to copilot-pat-pool October 29, 2026 17:39 — with GitHub Actions Inactive
@halter73

Copy link
Copy Markdown
Member

/backport to release/11.0

@github-actions

Copy link
Copy Markdown
Contributor

Started backporting to release/11.0 (link to workflow run)

@halter73
halter73 temporarily deployed to copilot-pat-pool October 29, 2026 17:43 — with GitHub Actions Inactive
@halter73

Copy link
Copy Markdown
Member

/backport to release/10.0

@github-actions

Copy link
Copy Markdown
Contributor

Started backporting to release/10.0 (link to workflow run)

@github-actions

Copy link
Copy Markdown
Contributor

✅ No documentation PR was created.

Confidence that documentation is needed: 5%

No docs needed: internal Kestrel HTTP/2 bug fix restoring expected behavior.

Documentation surfaces considered

  • Conceptual article: Not required — Internal fix to HTTP/2 producer scheduling restoring expected behavior; no public API or configuration change.
  • Migration guidance: Not required — No action needed by users upgrading.
  • Breaking change: Not required — No compatibility impact; hang bug fixed.

@halter73
halter73 temporarily deployed to copilot-pat-pool October 29, 2026 17:44 — with GitHub Actions Inactive
@Misiu

Misiu commented Oct 29, 2026

Copy link
Copy Markdown

@halter73 thank you for looking at this PR.
Which versions of .NET will include this fix?

@halter73

Copy link
Copy Markdown
Member

/backport to release/8.0

@github-actions

Copy link
Copy Markdown
Contributor

Started backporting to release/8.0 (link to workflow run)

hizkifw added a commit to hizkifw/paduraksa that referenced this pull request Nov 14, 2026
… a reused stream (dotnet/aspnetcore#69690, not yet in 10.0): the stream's stale schedule flag is cleared when a request starts, the workaround turns itself off once Kestrel has the fix, and a test makes the race happen every time
wtgodbe pushed a commit that referenced this pull request Nov 16, 2026
…9690) (#70099)

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: Daniel Dror <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Stephen Halter <[email protected]>
wtgodbe pushed a commit that referenced this pull request Nov 16, 2026
…9690) (#70100)

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: Daniel Dror <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Stephen Halter <[email protected]>

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 6d4028eb Deployed Oct 29, 2026 by halter73 via conclusion #125
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-networking Includes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions community-contribution Indicates that the PR has been added by a community member pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Kestrel occasionally losing zero-size GRPC responses

5 participants