Repository navigation
Handle connection loss during WebSocket write backpressure - #3050
Conversation
asyncio does not call resume_writing() when a transport is lost while paused. Set writable during connection_lost() so an ASGI send blocked on backpressure does not leak indefinitely.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughBoth websocket protocol implementations now detect transport closure during sends. The wsproto implementation also releases blocked sends when connection loss occurs. The regression test covers both implementations and verifies the expected ChangesWebSocket Connection-Loss Backpressure
Estimated code review effort: 2 (Simple) | ~10 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Comment |
|
📖 Docs preview: https://41f42e28-uvicorn.marcelotryle.workers.dev |
Merging this PR will improve performance by 12.26%
|
| Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|
| ⚡ | test_bench_fragmented_body[httptools] |
2.2 ms | 1.9 ms | +14.01% |
| ⚡ | test_bench_fragmented_body[zttp] |
2.8 ms | 2.5 ms | +10.54% |
Tip
Curious why this is faster? Comment @codspeedbot explain why this is faster on this PR, or directly use the CodSpeed MCP with your agent.
Comparing fix/wsproto-unblock-paused-send (2a33226) with main (e16a69b)
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 27a8e8bc7b
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
|
||
| self.handshake_complete = True | ||
| # asyncio never calls resume_writing() when a paused transport is lost. | ||
| self.writable.set() |
There was a problem hiding this comment.
Fail sends awakened after connection loss
When an established wsproto connection drops while backpressure has blocked send(), setting this event wakes the coroutine but does not make it fail. connection_lost() leaves the wsproto connection state usable, so the resumed websocket.send serializes its message, skips the write because the transport is closing, and returns successfully. A send-only producer can consequently continue looping—potentially consuming CPU—instead of receiving the OSError already expected by test_client_connection_lost_on_send; record the lost state and raise ClientDisconnected after waking.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
All reported issues were addressed across 2 files
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
…-paused-send # Conflicts: # tests/protocols/test_websocket.py
Generalize the test merged in #3048 instead of maintaining a separate wsproto-only test. The existing ws_protocol_cls fixture already skips wsproto when the optional dependency is unavailable.
After connection_lost wakes a sender blocked on backpressure, check whether the transport is closing before serializing the message. This prevents unwritten sends from returning successfully without adding duplicate disconnected state.
Only apply the transport disconnect check before a close frame has been sent, preserving the existing RuntimeError for ASGI messages sent after websocket.close. The protocol-library exception handlers are now defensive fallbacks because the transport check catches normal connection-loss paths first.
Notify each SansIO state machine that the input stream ended before waking paused senders. The resumed send then follows the existing InvalidState or LocalProtocolError conversion to ClientDisconnected, allowing the shared behavior test to cover both implementations without transport-state checks or coverage exclusions. Ignore a pending proactor read delivered after parser EOF.
Mirror the HTTP protocol design: mark each WebSocket protocol disconnected in connection_lost(), wake paused senders, and have send() raise ClientDisconnected after waking. Keep the existing protocol-library exception conversions for the separate window where the peer closes the WebSocket before connection_lost() runs, covered by a shared behavioral test.
Summary
Handle the race where a WebSocket connection is lost while an ASGI
send()is blocked by write backpressure.When asyncio loses a paused transport, it calls
connection_lost()without callingresume_writing(). Without intervention, a sender blocked inawait self.writable.wait()remains stuck indefinitely. Waking it without recording connection loss can also let the pending send return successfully even though its message was never written.Changes
disconnectedstate to both SansIO WebSocket implementations, matching Uvicorn’s HTTP protocol design.disconnectedbefore waking paused senders fromconnection_lost().writable.wait(), raiseClientDisconnectedwhen connection loss woke the sender.writablein wsprotoconnection_lost(), matching the flow-control behavior added towebsockets-sansioin Add missing write flow control towebsockets-sansio#3048.InvalidState/LocalProtocolErrorconversions for the separate window where the peer closes the WebSocket beforeconnection_lost()runs.websockets-sansio#3048 to both implementations and assert that a sender woken by connection loss raisesOSError.connection_lost(), also raisesOSErrorthrough the existing protocol-specific exception conversions.No parser EOF manipulation, late-read exception handling, implementation-specific test branches, or coverage exclusions are needed.
Optional dependency
The tests use the existing
ws_protocol_clsfixture, which automatically skips wsproto parameters when wsproto is not installed.Verification