Preserve actual close code during shutdown in websockets implementation#2865
Closed
hrv-dys wants to merge 2 commits intoKludex:mainfrom
Closed
Preserve actual close code during shutdown in websockets implementation#2865hrv-dys wants to merge 2 commits intoKludex:mainfrom
hrv-dys wants to merge 2 commits intoKludex:mainfrom
Conversation
When a ConnectionClosed exception is caught in asgi_receive() and the server is shutting down, use the actual close_code from the connection if it represents a real close frame (not 1005/1006), falling back to 1012 only when no close frame was received. Co-Authored-By: Harsha Vardhan <harsha@example.com>
The `not in` check doesn't narrow `int | None` to `int` for mypy. Use isinstance(close_code, int) to properly narrow the type. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
In
websockets_impl.py, when aConnectionClosedexception is caught duringasgi_receive()and the server is shutting down (ws_server.closingis True),the disconnect event always reports code 1012 ("Service Restart"), regardless
of the actual close code from the connection.
This means if a client sends a normal close (1000) that races with the
server's shutdown close (1012), the app always sees 1012 — losing the
information that the client actually closed cleanly.
This fix uses the actual
close_codewhen available, falling back to 1012only when no close code was received from the connection. In practice:
fail_connection(1012)→ code = 1012 ✓Belief that guided this fix: don't use a single flag
(
ws_server.closing) to overwrite all connection state during shutdown,because it causes
send()andreceive()to lose information about whatactually happened on the wire.
Test plan
tests/protocols/test_websocket.pypasses