Skip to content

[HTTP/2] HttpClient throws STREAM_CLOSED when server completes response + resets stream while client is still uploading a large request body #135063

Description

@funkcj

Related issue

This looks like a concrete, reliably-reproducible instance of the bug class described in #57617 ("Race between reading response and reset?"), which was closed in Sep 2025 as "not actionable" due to lack of a reliable repro. This issue provides one.

Description

When a server validates a request quickly, sends its final response, and resets the HTTP/2 stream with RST_STREAM(NO_ERROR) before the client has finished uploading a large request body, HttpClient/SocketsHttpHandler does not gracefully discard the remaining unsent body and return the already-complete response. Instead, it continues attempting to send DATA frames, the server (which has already closed the stream) replies with a second RST_STREAM(STREAM_CLOSED), and this is surfaced to the caller as a hard failure:

System.Net.Http.HttpRequestException: Error while copying content to a stream.
 ---> System.Net.Http.HttpProtocolException: The HTTP/2 server reset the stream. HTTP/2 error code 'STREAM_CLOSED' (0x5). (HttpProtocolError)

Per RFC 9113 §8.1, a server is permitted to send a complete response and reset the request stream to signal "stop sending the rest of the body" — the client is expected to treat the already-received response as valid, not fail the request.

Repro

Reliable, minimal repro against a real public HTTP/2 endpoint (https://api.githubcopilot.com/chat/completions, which returns a fast 400 Bad Request for malformed JSON bodies — no auth/API key required to observe the failure since the rejection happens before request validation of auth):

  1. POST a body of increasing size ({"x":"<N bytes of 'y'>"}) with HttpVersionPolicy.RequestVersionExact + HTTP/2.
  2. Below ~114688 bytes: body finishes uploading before the server's early-rejection response + reset arrives → no error.
  3. At/above ~114688 bytes: body upload is still in progress when the server's response + first reset arrives → client keeps writing → second reset → exception. Failure rate is intermittent (30-70%) depending on timing, not deterministic by size alone.
  4. A side-by-side run of the same payload through curl --http2 (nghttp2-based) at the exact same moment never fails — confirming the server behavior is spec-compliant and the bug is specific to SocketsHttpHandler's handling of this race.
  5. Reproduces cross-platform. The identical race also reproduces on Linux (WSL2, Ubuntu 26.04, .NET 10.0.401 SDK, invariant globalization), confirming this is in the shared managed Http2Connection/Http2Stream code, not a Windows-specific transport artifact. The exact size threshold differs by platform (Linux's socket/TLS stack is apparently fast enough that smaller bodies usually finish uploading before the race window closes): 0/70 failures from 64KB-160KB, but reliable, repeated failures from 256KB up through 16MB, with the identical STREAM_CLOSED signature and identical frame sequence (RST_STREAM(NoError) immediately followed by continued DATA frames then RST_STREAM(StreamClosed)).

Captured via a custom EventListener on Private.InternalDiagnostics.System.Net.Http (frame-level trace attached below) rather than packet capture, which shows the exact frame sequence:

Frame: StreamId=1; Type=Data; Flags=Ack; PayloadLength=51                         (response headers+body already complete, 400 Bad Request)
ProcessRstStreamFrame protocolError=NoError                                       (server: "done, stop sending rest of body")
ProcessOutgoingFramesAsync writeBytes=16393                                       (client keeps writing DATA frames anyway)
ProcessRstStreamFrame protocolError=StreamClosed                                  (server: stream no longer exists)
OnReset resetException=... 'STREAM_CLOSED' (0x5)
SendRequestBodyAsync Failed to send request body: ...STREAM_CLOSED...
HandleFailure System.Net.Http.HttpRequestException: Error while copying content to a stream.

Repro scripts

Four PowerShell 7+ scripts (Windows) plus one minimal C# console app (Linux), self-contained, no external dependencies besides curl (for the control test):

  • http_version_test.ps1 — sweeps body sizes 64KB-16MB over both HTTP/2 and HTTP/1.1 via HttpClient, shows failures start ~114KB on HTTP/2 only.
  • http_version_test_curl.ps1 — identical sweep via curl --http2/--http1.1 as a non-.NET control; 0 failures across all sizes/runs.
  • compare_http2.ps1 — runs both HttpClient and curl back-to-back at the same size/moment; curl never fails while HttpClient fails 30-70% of the time from ~114KB up, proving it's not network/timing/server flakiness.
  • capture_http2_trace.ps1 — adds the EventListener frame-level trace capture shown above (Windows).
  • wsl-http2-repro/Program.cs + .csproj — equivalent minimal C# console app for the Linux/WSL cross-check (same EventListener trace capture, no PowerShell dependency).

(Attach all scripts to the actual GitHub issue when filing.)

Expected behavior

When the server has already sent a complete response (headers + body/trailers with END_STREAM) and resets the stream with NO_ERROR while the client is still sending request body data, HttpClient should discard the unsent remainder of the body and return the response it already received, rather than throwing.

Actual behavior

HttpClient.SendAsync throws HttpRequestException → HttpProtocolException (STREAM_CLOSED), discarding the already-fully-received valid response.

Environment

  • .NET runtime hosting pwsh 7.6.6: 10.0.12 (confirmed via [System.Environment]::Version) on Windows 11 24H2 (10.0.26300) — i.e. this reproduces on current .NET 10, well past the .NET 6.0 fix for HttpClient Http/2 doesn't flush frames when hitting the window limit #52451, and is a distinct bug from that one.
  • Also reproduces on .NET 10.0.401 SDK on WSL2 Ubuntu 26.04 (Linux), confirming it's not Windows-specific.
  • Server: GitHub's api.githubcopilot.com HTTP/2 edge (exact server software unknown, likely Kestrel/Envoy-fronted)

Impact

This is believed to be the root cause of intermittent HTTP/2 timeouts/failures seen in production for VS Code Copilot's own HTTP/2 traffic against api.githubcopilot.com, significant enough that the current workaround is to force all Copilot network traffic in VS Code to use HTTP/1.1 (http.electronFetch: false, pinning to node-fetch) instead of using HTTP/2 via .NET/Node's native fetch implementations that hit this bug.

Activity

  1. added
    untriaged
    on Oct 1, 2026
  2. funkcj commented on Oct 1, 2026

    @funkcj
    Author

    http2-stream-closed-repro.zip

    added test scripts.

  3. dotnet-policy-service commented on Oct 1, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @karelz, @dotnet/ncl
    See info in area-owners.md if you want to be subscribed.

  4. removed
    untriaged
    on Oct 2, 2026
  5. added this to the 12.0.0 milestone on Oct 2, 2026
  6. wfurt commented on Oct 2, 2026

    @wfurt
    Member

    we should investigate if we get repro.

  7. alexsorokoletov commented on Oct 25, 2026

    @alexsorokoletov
    Contributor

    I believe this is the cause, and I have a deterministic repro against a raw h2c server on localhost. It reproduces on runtime 10.0.3 and 10.0.13.

    Sequence. The client POSTs a body; the server sends a complete response and then RST_STREAM(NO_ERROR) (RFC 9113 §8.1). Http2Stream.OnReset marks the request body abandoned and cancels it (L981-L996), but until the body task's catch runs, the request side still counts as in progress. If a second event arrives in that window — RST_STREAM(STREAM_CLOSED) for DATA frames already in flight (your trace shows exactly this), or GOAWAY + FIN — the guard at L956-L966 no longer matches, the else branch sets _resetException, and Cancel() → CancelResponseBody discards the fully buffered response (L455-L470). SendAsync then returns, and reading the content throws Error while copying content to a stream / STREAM_CLOSED. The change for #30662 covered only the first reset.

    Repro. The interleaving is pinned without timing: the request body is a non-duplex StreamContent whose stream blocks on a gate, and the test opens the gate only after a PING ACK proves the client has processed the server's frames.

    client: SendAsync(POST /upload, HTTP/2 exact, StreamContent(gated stream))   // stream 1
    gated stream: returns one 1 KiB chunk, then blocks on Gate
    server (TcpListener, h2c prior knowledge):
      read preface; send SETTINGS; ack client SETTINGS
      send HEADERS(stream 1, :status 200, END_HEADERS)
      send DATA(stream 1, "hello", END_STREAM)            // response complete
      send RST_STREAM(stream 1, NO_ERROR)                 // "stop the upload, the response stands"
      send RST_STREAM(stream 1, STREAM_CLOSED)            // second late event
      send PING; wait for PING ACK                        // client has processed all frames above
    test: Gate.SetResult()                                // body task now observes its canceled token
    assert: response.StatusCode == 200 && await response.Content.ReadAsStringAsync() == "hello"
    actual: HttpRequestException "Error while copying content to a stream" (STREAM_CLOSED)
    

    Results: red for {second RST_STREAM(STREAM_CLOSED), GOAWAY + FIN} × {ResponseHeadersRead, ResponseContentRead}. The control with a single RST_STREAM(NO_ERROR) passes.

  8. wolfgangcolsman commented on Nov 3, 2026

    @wolfgangcolsman

    We hit what looks like the same race from the gRPC side, reported as #136834 (closed as a duplicate of this one).

    Our case: a Kestrel gRPC service ends each long-lived duplex streaming call with Unavailable and a message in the trailers, then stops Kestrel. The Grpc.Net.Client side sometimes gets Internal with "The HTTP/2 server closed the connection ... NO_ERROR" instead of the Unavailable status, more often on a busy machine. The client is still sending on the request stream when the response trailers arrive, so it looks like the request-body copy fails after the response has already completed, as described here.

    #136834 has a small standalone repro (Kestrel + Grpc.Net.Client only) that failed 2 and 8 times in two local batches of 200 runs, in case it helps confirm the fix.

  9. added a commit that references this issue on Nov 25, 2026
    3ad46e5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions