Skip to content

Fix TCPConnector.close() resolver race on non-cached path (#12497)#12498

Open
masonwilde wants to merge 7 commits into
aio-libs:masterfrom
masonwilde:fix-connector-resolver-close-race
Open

Fix TCPConnector.close() resolver race on non-cached path (#12497)#12498
masonwilde wants to merge 7 commits into
aio-libs:masterfrom
masonwilde:fix-connector-resolver-close-race

Conversation

@masonwilde
Copy link
Copy Markdown

What do these changes do?

Fix a race condition in TCPConnector.close() where the AsyncResolver's internal _resolver reference is nullified before the connector is marked closed (_closed = True). When an in-flight connection is suspended in a trace callback at the time of close, it resumes and calls self._resolver.resolve() on None, producing AttributeError: 'NoneType' object has no attribute 'getaddrinfo'.

Two changes:

  1. Reorder TCPConnector.close() — call super().close() before self._resolver.close() so _closed is True before the resolver is torn down.
  2. Add _closed guard in _resolve_host() — on the non-cached path (use_dns_cache=False), check self._closed after trace callbacks yield and before calling self._resolver.resolve(). The cached path is already handled by _close_immediately() which cancels tracked _resolve_host_tasks.

Are there changes in behavior for the user?

Connections that previously crashed with AttributeError during a concurrent session.close() now raise ClientConnectionError("Connector is closed").

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

No. The close reorder is a two-line swap with no new API surface. The _closed guard is a single conditional in an existing method. Both follow patterns already used elsewhere in the connector (e.g. _close_immediately cancelling tracked resolve tasks on the cached path).

Related issue number

Fixes #12497

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.

@psf-chronographer psf-chronographer Bot added the bot:chronographer:provided There is a change note present in this PR label May 11, 2026
Comment thread tests/test_connector.py
await closed_event.wait()

token: ResolveResult = {
"hostname": "localhost",
@codecov
Copy link
Copy Markdown

codecov Bot commented May 11, 2026

Codecov Report

❌ Patch coverage is 96.29630% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 98.94%. Comparing base (65b42bb) to head (13a63bf).
⚠️ Report is 51 commits behind head on master.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
tests/test_connector.py 95.65% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #12498      +/-   ##
==========================================
+ Coverage   98.55%   98.94%   +0.39%     
==========================================
  Files         131      131              
  Lines       46558    46583      +25     
  Branches     2409     2410       +1     
==========================================
+ Hits        45883    46092     +209     
+ Misses        528      368     -160     
+ Partials      147      123      -24     
Flag Coverage Δ
Autobahn 22.42% <7.40%> (-0.02%) ⬇️
CI-GHA 98.92% <96.29%> (+0.91%) ⬆️
OS-Linux 98.66% <96.29%> (+0.66%) ⬆️
OS-Windows 97.03% <96.29%> (?)
OS-macOS 97.93% <96.29%> (?)
Py-3.10.11 97.42% <96.29%> (?)
Py-3.10.20 97.91% <96.29%> (+0.65%) ⬆️
Py-3.11.15 98.16% <96.29%> (+0.65%) ⬆️
Py-3.11.9 97.67% <96.29%> (?)
Py-3.12.10 97.76% <96.29%> (?)
Py-3.12.13 98.25% <96.29%> (?)
Py-3.13.13 98.48% <96.29%> (?)
Py-3.14.4 98.45% <96.29%> (+0.88%) ⬆️
Py-3.14.5t 97.56% <96.29%> (?)
Py-pypy3.11.15-7.3.21 97.41% <96.29%> (?)
VM-macos 97.93% <96.29%> (?)
VM-ubuntu 98.66% <96.29%> (+0.66%) ⬆️
VM-windows 97.03% <96.29%> (?)
cython-coverage 37.96% <7.40%> (-0.03%) ⬇️

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.

@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented May 11, 2026

Merging this PR will improve performance by 8.79%

⚡ 2 improved benchmarks
✅ 70 untouched benchmarks
⏩ 69 skipped benchmarks1

Performance Changes

Benchmark BASE HEAD Efficiency
test_client_receive_large_websocket_compressed_messages[zlib_ng.zlib_ng] 29.9 ms 27.5 ms +8.81%
test_client_send_large_websocket_compressed_messages[zlib_ng.zlib_ng] 30 ms 27.6 ms +8.77%

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 masonwilde:fix-connector-resolver-close-race (13a63bf) with master (9bc498b)2

Open in CodSpeed

Footnotes

  1. 69 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

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

Comment thread tests/test_connector.py
Comment on lines +4710 to +4712
def __init__(self) -> None:
"""Dummy"""

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Probably makes sense to remove this and pass the necessary arguments just to be sure we don't end up with any other errors in future caused by the missing attributes.

Comment thread tests/test_connector.py
Comment on lines +4732 to +4733
with mock.patch.object(connector._resolver, "resolve", fake_resolve):
with mock.patch.object(connector._resolver, "close", mock.AsyncMock()):
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We should use autospec/spec_set here. Something like:

Suggested change
with mock.patch.object(connector._resolver, "resolve", fake_resolve):
with mock.patch.object(connector._resolver, "close", mock.AsyncMock()):
with mock.patch.object(connector._resolver, "resolve", autospec=True, spec_set=True) as m:
m.return_value = [token]
with mock.patch.object(connector._resolver, "close", autospec=True, spec_set=True):

@Dreamsorcerer Dreamsorcerer added the pr-unfinished The PR is unfinished and may need a volunteer to complete it label May 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:chronographer:provided There is a change note present in this PR pr-unfinished The PR is unfinished and may need a volunteer to complete it

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TCPConnector.close() race: AttributeError on in-flight resolve with aiodns

3 participants