Skip to content

Handle connection loss during WebSocket write backpressure - #3050

Merged
Kludex merged 10 commits into
mainfrom
fix/wsproto-unblock-paused-send
Jul 31, 2026
Merged

Kludex merged 10 commits into
mainfrom
fix/wsproto-unblock-paused-send

Conversation

@Kludex

@Kludex Kludex commented Jul 30, 2026 •

Copy link
Copy Markdown
Owner

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 calling resume_writing(). Without intervention, a sender blocked in await 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

  • Add explicit disconnected state to both SansIO WebSocket implementations, matching Uvicorn’s HTTP protocol design.
  • Set disconnected before waking paused senders from connection_lost().
  • After writable.wait(), raise ClientDisconnected when connection loss woke the sender.
  • Set writable in wsproto connection_lost(), matching the flow-control behavior added to websockets-sansio in Add missing write flow control to websockets-sansio #3048.
  • Keep the existing InvalidState / LocalProtocolError conversions for the separate window where the peer closes the WebSocket before connection_lost() runs.
  • Generalize the flow-control test merged in Add missing write flow control to websockets-sansio #3048 to both implementations and assert that a sender woken by connection loss raises OSError.
  • Add one shared behavioral test showing that a send after a peer close, but before connection_lost(), also raises OSError through 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_cls fixture, which automatically skips wsproto parameters when wsproto is not installed.

Verification

  • Relevant shared tests: 18 passed.
  • Full suite under coverage: 1197 passed, 17 skipped, 100% coverage.
  • Ruff and mypy clean.

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.
@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Both 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 OSError.

Changes

WebSocket Connection-Loss Backpressure

Layer / File(s) Summary
Handle transport loss during sends
uvicorn/protocols/websockets/wsproto_impl.py, uvicorn/protocols/websockets/websockets_sansio_impl.py
The wsproto implementation sets writable during connection_lost(). Both implementations raise ClientDisconnected when the transport is closing after the writable wait. Existing exception conversion paths are excluded from coverage.
Verify blocked-send failure
tests/protocols/test_websocket.py
The connection-loss backpressure test runs against both websocket protocol implementations and asserts that the blocked send fails with OSError.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

  • Kludex/uvicorn#3048: Both changes modify websocket send backpressure and connection-loss handling.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: handling connection loss during WebSocket writes blocked by backpressure.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/wsproto-unblock-paused-send

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

📖 Docs preview: https://41f42e28-uvicorn.marcelotryle.workers.dev

@codspeed

codspeed Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Merging this PR will improve performance by 12.26%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 2 improved benchmarks
✅ 32 untouched benchmarks

Performance Changes

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)

Open in CodSpeed

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

All reported issues were addressed across 2 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Kludex added 2 commits July 30, 2026 15:03
…-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.
@Kludex Kludex changed the title Unblock paused wsproto senders on connection loss Fail paused WebSocket sends after connection loss Jul 31, 2026
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.
@Kludex Kludex changed the title Fail paused WebSocket sends after connection loss Handle connection loss during WebSocket write backpressure Jul 31, 2026
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.
@Kludex
Kludex merged commit e148451 into main Jul 31, 2026
43 of 45 checks passed
@Kludex
Kludex deleted the fix/wsproto-unblock-paused-send branch July 31, 2026 18:37

This branch was successfully deployed

1 active deployment
cloudflare — 2a332266 Deployed Jul 31, 2026 by Kludex via docs-preview #862
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant