Skip to content

Raise ConnectionResetError if transport is None#11761

Merged
Dreamsorcerer merged 10 commits intoaio-libs:masterfrom
agners:use-runtime-exception-if-transport-is-none
Mar 27, 2026
Merged

Raise ConnectionResetError if transport is None#11761
Dreamsorcerer merged 10 commits intoaio-libs:masterfrom
agners:use-runtime-exception-if-transport-is-none

Conversation

@agners
Copy link
Copy Markdown
Contributor

@agners agners commented Nov 13, 2025

What do these changes do?

When a client disconnects immediately after connecting, the transport might become None. This should not lead to an assertion, since this can happen in real-world scenarios. Use a RuntimeException instead.

Are there changes in behavior for the user?

A WebSocket connection disconnecting early will no longer lead to a assertion but a RuntimeException instead.

Is it a substantial burden for the maintainers to support this?

Related issue number

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt
    • The format is <Name> <Surname>.
    • Please keep alphabetical order, the file is sorted by names.
  • Add a new news fragment into the CHANGES/ folder
    • name it <issue_or_pr_num>.<type>.rst (e.g. 588.bugfix.rst)

    • if you don't have an issue number, change it to the pull request
      number after creating the PR

      • .bugfix: A bug fix for something the maintainers deemed an
        improper undesired behavior that got corrected to match
        pre-agreed expectations.
      • .feature: A new behavior, public APIs. That sort of stuff.
      • .deprecation: A declaration of future API removals and breaking
        changes in behavior.
      • .breaking: When something public is removed in a breaking way.
        Could be deprecated in an earlier release.
      • .doc: Notable updates to the documentation structure or build
        process.
      • .packaging: Notes for downstreams about unobvious side effects
        and tooling. Changes in the test invocation considerations and
        runtime assumptions.
      • .contrib: Stuff that affects the contributor experience. e.g.
        Running tests, building the docs, setting up the development
        environment.
      • .misc: Changes that are hard to assign to any of the above
        categories.
    • Make sure to use full sentences with correct case and punctuation,
      for example:

      Fixed issue with non-ascii contents in doctest text files
      -- by :user:`contributor-gh-handle`.

      Use the past tense or the present tense a non-imperative mood,
      referring to what's changed compared to the last released version
      of this project.

@agners agners requested a review from asvetlov as a code owner November 13, 2025 15:27
@codspeed-hq
Copy link
Copy Markdown

codspeed-hq bot commented Nov 13, 2025

Merging this PR will not alter performance

✅ 59 untouched benchmarks


Comparing agners:use-runtime-exception-if-transport-is-none (96bfa33) with master (e04da11)1

Open in CodSpeed

Footnotes

  1. No successful run was found on master (9ee2c3a) during the generation of this report, so e04da11 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report.

@Dreamsorcerer
Copy link
Copy Markdown
Member

The assertion is because the code expects it to never be None in this scenario, so I'm not sure this is the correct fix. I'll use your test and try to figure out if there's a better solution later.

@Dreamsorcerer
Copy link
Copy Markdown
Member

I'll use your test and try to figure out if there's a better solution later.

Wait, sorry, your test literally just assigns the transport to None. We need the actual set of steps that causes this to happen in production.

@Dreamsorcerer
Copy link
Copy Markdown
Member

Dreamsorcerer commented Nov 13, 2025

Running through the code, I think the steps that may reproduce this would look like:

  • Client creates a connection.
  • Handler pauses (asyncio.sleep() for a test)
  • Client disconnects
  • Handler calls ws.prepare().

I think the WebSocketWriter that is returned from .prepare() is responsible for raising exceptions related to the client disconnecting. Therefore, my first thought is that we should probably figure out a fix that ensures the (potentially closed) transport is always available inside .prepare().

@Dreamsorcerer
Copy link
Copy Markdown
Member

I think setting the transport to None is something that has been copied from asyncio, but I'm not clear if there's a real reason for that. Maybe we can just avoid setting to None, which would greatly simplify our type checking. @bdraco Any thoguhts?

@agners
Copy link
Copy Markdown
Contributor Author

agners commented Nov 13, 2025

Wait, sorry, your test literally just assigns the transport to None. We need the actual set of steps that causes this to happen in production.

Yeah sorry, I realize this test is not ideal, but triggering a race condition is also not really a good idea for a pytest.

Running through the code, I think the steps that may reproduce this would look like:

Right, I think that is pretty much the sequence we see in production. I have a reproducer which allows to trigger the bug in our use case (Home Assistant Supervisor): home-assistant/supervisor#6241, specifically home-assistant/supervisor#6241 (comment).

I think setting the transport to None is something that has been copied from asyncio, but I'm not clear if there's a real reason for that. Maybe we can just avoid setting to None, which would greatly simplify our type checking. @bdraco Any thoguhts?

Hm, I guess that would make the transport to raise a closed connection exception or similar, this sounds like a good approach to me.

@Dreamsorcerer
Copy link
Copy Markdown
Member

triggering a race condition is also not really a good idea for a pytest

Following the steps I outlined, we should be able to reproduce it with minimal timing concerns. We have many similar tests that reproduce other race conditions.

When a client disconnects immediately after connecting, the transport
might become None. Replace the assert with a ConnectionResetError,
which is consistent with the existing aiohttp exception hierarchy and
the documented guidance to handle OSError for peer disconnection.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@agners agners force-pushed the use-runtime-exception-if-transport-is-none branch from 9f20389 to ecc2177 Compare March 3, 2026 22:38
@psf-chronographer psf-chronographer bot added the bot:chronographer:provided There is a change note present in this PR label Mar 3, 2026
@agners
Copy link
Copy Markdown
Contributor Author

agners commented Mar 3, 2026

Following the steps I outlined, we should be able to reproduce it with minimal timing concerns. We have many similar tests that reproduce other race conditions.

I've added such a test, along with using an asyncio.Event to strictly enforce the required interleaving.

@Dreamsorcerer
Copy link
Copy Markdown
Member

I've added such a test, along with using an asyncio.Event to strictly enforce the required interleaving.

Perfect, thanks for that. I'll have a little play with it later and see if we can get rid of the None checks.

@agners agners changed the title Raise RuntimeError if transport is None Raise ConnectionResetError if transport is None Mar 9, 2026
@Dreamsorcerer
Copy link
Copy Markdown
Member

I had a little go in #12244. It's pretty awkward to remove the None entirely, as you'd be left with an AttributeError until connection_made() is called to set the transport initially. I think we'll just leave it as is for now.

Co-authored-by: Sam Bull <aa6bs0@sambull.org>
@Dreamsorcerer Dreamsorcerer added backport-3.13 Trigger automatic backporting to the 3.13 release branch by Patchback robot backport-3.14 Trigger automatic backporting to the 3.14 release branch by Patchback robot labels Mar 15, 2026
@codecov
Copy link
Copy Markdown

codecov bot commented Mar 15, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.10%. Comparing base (a6687c2) to head (96bfa33).
⚠️ Report is 6 commits behind head on master.
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@           Coverage Diff           @@
##           master   #11761   +/-   ##
=======================================
  Coverage   99.10%   99.10%           
=======================================
  Files         130      130           
  Lines       45366    45452   +86     
  Branches     2397     2399    +2     
=======================================
+ Hits        44959    45046   +87     
+ Misses        276      275    -1     
  Partials      131      131           
Flag Coverage Δ
CI-GHA 98.96% <100.00%> (+<0.01%) ⬆️
OS-Linux 98.70% <100.00%> (+<0.01%) ⬆️
OS-Windows 96.98% <100.00%> (+0.01%) ⬆️
OS-macOS 97.86% <100.00%> (+<0.01%) ⬆️
Py-3.10.11 97.42% <100.00%> (+<0.01%) ⬆️
Py-3.10.20 97.89% <100.00%> (+<0.01%) ⬆️
Py-3.11.15 98.10% <100.00%> (+<0.01%) ⬆️
Py-3.11.9 97.63% <100.00%> (+<0.01%) ⬆️
Py-3.12.10 97.72% <100.00%> (+<0.01%) ⬆️
Py-3.12.13 98.19% <100.00%> (+0.01%) ⬆️
Py-3.13.12 98.44% <100.00%> (+<0.01%) ⬆️
Py-3.14.3 98.50% <100.00%> (+<0.01%) ⬆️
Py-3.14.3t 97.50% <100.00%> (+0.01%) ⬆️
Py-pypy3.11.13-7.3.20 ?
Py-pypy3.11.15-7.3.21 97.53% <100.00%> (?)
VM-macos 97.86% <100.00%> (+<0.01%) ⬆️
VM-ubuntu 98.70% <100.00%> (+<0.01%) ⬆️
VM-windows 96.98% <100.00%> (+0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

agners and others added 3 commits March 27, 2026 01:02
Adds test_sendfile_after_client_disconnect to cover the race condition
in web_fileresponse.py where the client disconnects before sendfile()
runs. Uses the same pattern as test_prepare_after_client_disconnect.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@Dreamsorcerer Dreamsorcerer merged commit b26c9ae into aio-libs:master Mar 27, 2026
73 of 79 checks passed
@patchback
Copy link
Copy Markdown
Contributor

patchback bot commented Mar 27, 2026

Backport to 3.13: 💔 cherry-picking failed — conflicts found

❌ Failed to cleanly apply b26c9ae on top of patchback/backports/3.13/b26c9aee4cf1cb280fa771855ab7be95f1ae1d22/pr-11761

Backporting merged PR #11761 into master

  1. Ensure you have a local repo clone of your fork. Unless you cloned it
    from the upstream, this would be your origin remote.
  2. Make sure you have an upstream repo added as a remote too. In these
    instructions you'll refer to it by the name upstream. If you don't
    have it, here's how you can add it:
    $ git remote add upstream https://github.com/aio-libs/aiohttp.git
  3. Ensure you have the latest copy of upstream and prepare a branch
    that will hold the backported code:
    $ git fetch upstream
    $ git checkout -b patchback/backports/3.13/b26c9aee4cf1cb280fa771855ab7be95f1ae1d22/pr-11761 upstream/3.13
  4. Now, cherry-pick PR Raise ConnectionResetError if transport is None #11761 contents into that branch:
    $ git cherry-pick -x b26c9aee4cf1cb280fa771855ab7be95f1ae1d22
    If it'll yell at you with something like fatal: Commit b26c9aee4cf1cb280fa771855ab7be95f1ae1d22 is a merge but no -m option was given., add -m 1 as follows instead:
    $ git cherry-pick -m1 -x b26c9aee4cf1cb280fa771855ab7be95f1ae1d22
  5. At this point, you'll probably encounter some merge conflicts. You must
    resolve them in to preserve the patch from PR Raise ConnectionResetError if transport is None #11761 as close to the
    original as possible.
  6. Push this branch to your fork on GitHub:
    $ git push origin patchback/backports/3.13/b26c9aee4cf1cb280fa771855ab7be95f1ae1d22/pr-11761
  7. Create a PR, ensure that the CI is green. If it's not — update it so that
    the tests and any other checks pass. This is it!
    Now relax and wait for the maintainers to process your pull request
    when they have some cycles to do reviews. Don't worry — they'll tell you if
    any improvements are necessary when the time comes!

🤖 @patchback
I'm built with octomachinery and
my source is open — https://github.com/sanitizers/patchback-github-app.

@patchback
Copy link
Copy Markdown
Contributor

patchback bot commented Mar 27, 2026

Backport to 3.14: 💔 cherry-picking failed — conflicts found

❌ Failed to cleanly apply b26c9ae on top of patchback/backports/3.14/b26c9aee4cf1cb280fa771855ab7be95f1ae1d22/pr-11761

Backporting merged PR #11761 into master

  1. Ensure you have a local repo clone of your fork. Unless you cloned it
    from the upstream, this would be your origin remote.
  2. Make sure you have an upstream repo added as a remote too. In these
    instructions you'll refer to it by the name upstream. If you don't
    have it, here's how you can add it:
    $ git remote add upstream https://github.com/aio-libs/aiohttp.git
  3. Ensure you have the latest copy of upstream and prepare a branch
    that will hold the backported code:
    $ git fetch upstream
    $ git checkout -b patchback/backports/3.14/b26c9aee4cf1cb280fa771855ab7be95f1ae1d22/pr-11761 upstream/3.14
  4. Now, cherry-pick PR Raise ConnectionResetError if transport is None #11761 contents into that branch:
    $ git cherry-pick -x b26c9aee4cf1cb280fa771855ab7be95f1ae1d22
    If it'll yell at you with something like fatal: Commit b26c9aee4cf1cb280fa771855ab7be95f1ae1d22 is a merge but no -m option was given., add -m 1 as follows instead:
    $ git cherry-pick -m1 -x b26c9aee4cf1cb280fa771855ab7be95f1ae1d22
  5. At this point, you'll probably encounter some merge conflicts. You must
    resolve them in to preserve the patch from PR Raise ConnectionResetError if transport is None #11761 as close to the
    original as possible.
  6. Push this branch to your fork on GitHub:
    $ git push origin patchback/backports/3.14/b26c9aee4cf1cb280fa771855ab7be95f1ae1d22/pr-11761
  7. Create a PR, ensure that the CI is green. If it's not — update it so that
    the tests and any other checks pass. This is it!
    Now relax and wait for the maintainers to process your pull request
    when they have some cycles to do reviews. Don't worry — they'll tell you if
    any improvements are necessary when the time comes!

🤖 @patchback
I'm built with octomachinery and
my source is open — https://github.com/sanitizers/patchback-github-app.

@Dreamsorcerer
Copy link
Copy Markdown
Member

@agners If you've got the time to prepare the backports with the above instructions, that'd be really helpful.

agners added a commit to agners/aiohttp that referenced this pull request Mar 27, 2026
@agners
Copy link
Copy Markdown
Contributor Author

agners commented Mar 27, 2026

@agners If you've got the time to prepare the backports with the above instructions, that'd be really helpful.

Done: #12283

Dreamsorcerer pushed a commit that referenced this pull request Mar 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport-3.13 Trigger automatic backporting to the 3.13 release branch by Patchback robot backport-3.14 Trigger automatic backporting to the 3.14 release branch by Patchback robot bot:chronographer:provided There is a change note present in this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants