Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGES/12497.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Fixed ``AttributeError: 'NoneType' object has no attribute 'getaddrinfo'`` when
``TCPConnector.close()`` ran concurrently with an in-flight non-cached resolve
suspended inside a trace callback (e.g. ``on_dns_resolvehost_start``). The
owned resolver was torn down before the connector was marked closed, leaving
the resuming resolve to call a nullified backend. The connector is now marked
closed before the resolver is torn down, and the non-cached resolve path
raises ``ClientConnectionError("Connector is closed.")`` instead --
by :user:`jbbqqf`.
1 change: 1 addition & 0 deletions CONTRIBUTORS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ Jan Gosmann
Jarno Elonen
Jashandeep Sohi
Javier Torres
Jean-Baptiste Braun
Jean-Baptiste Estival
Jens Steinhauser
Jeonghun Lee
Expand Down
17 changes: 15 additions & 2 deletions aiohttp/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -1005,10 +1005,15 @@ async def close(self, *, abort_ssl: bool = False) -> None:
- If ssl_shutdown_timeout=0: connections are aborted
- If ssl_shutdown_timeout>0: graceful shutdown is performed
"""
if self._resolver_owner:
await self._resolver.close()
# Mark the connector as closed (and cancel any tracked resolve tasks in
# _close_immediately) BEFORE tearing down the owned resolver. Otherwise
# an in-flight non-cached resolve suspended inside a trace callback would
# wake up after self._resolver was nullified and crash with
# AttributeError instead of seeing the closed connector (see #12497).
# Use abort_ssl param if explicitly set, otherwise use ssl_shutdown_timeout default
await super().close(abort_ssl=abort_ssl or self._ssl_shutdown_timeout == 0)
if self._resolver_owner:
await self._resolver.close()

def _close_immediately(self, *, abort_ssl: bool = False) -> list[Awaitable[object]]:
for fut in chain.from_iterable(self._throttle_dns_futures.values()):
Expand Down Expand Up @@ -1062,6 +1067,14 @@ async def _resolve_host(
for trace in traces:
await trace.send_dns_resolvehost_start(host)

# If the connector was closed while a trace callback was suspended,
# the owned resolver may already have been torn down. Surface the
# closed state as ClientConnectionError instead of letting the
# resolver crash with AttributeError on its nullified backend
# (see #12497).
if self._closed:
raise ClientConnectionError("Connector is closed.")

res = await self._resolver.resolve(host, port, family=self._family)

if traces:
Expand Down
50 changes: 50 additions & 0 deletions tests/test_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -2844,6 +2844,56 @@ async def delay_resolve(*args: object, **kwargs: object) -> None:
await t


async def test_close_during_non_cached_resolve_raises_client_error(
make_client_request: _RequestMaker,
) -> None:
"""Regression test for #12497.

When ``use_dns_cache=False`` the resolve call is not tracked in
``_resolve_host_tasks``, so a request suspended inside a trace callback
right before the resolver call could previously resume after the owned
resolver had been torn down and crash with ``AttributeError`` on the
nullified backend. The teardown must instead surface a
``ClientConnectionError("Connector is closed.")`` to the caller, matching
the cached-path behavior.
"""
trace_yielded = asyncio.Event()

async def yielding_on_dns_start(
session: object, ctx: object, params: object
) -> None:
# Yield so close() can run while the in-flight resolve is suspended
# right between the trace callback and the resolver call.
trace_yielded.set()
await asyncio.sleep(0)

trace_config = aiohttp.TraceConfig()
trace_config.on_dns_resolvehost_start.append(yielding_on_dns_start)
trace_config.freeze()
trace_obj = Trace(
mock.Mock(),
trace_config,
trace_config.trace_config_ctx(),
)

conn = aiohttp.TCPConnector(use_dns_cache=False)
req = make_client_request(
"GET",
URL("http://example.com:80"),
loop=asyncio.get_running_loop(),
response_class=mock.Mock(),
)
task = asyncio.create_task(conn.connect(req, [trace_obj], ClientTimeout()))
# Let the request reach the trace-callback yield.
await trace_yielded.wait()

# Close while the resolve is suspended in the trace callback.
await conn.close()

with pytest.raises(aiohttp.ClientConnectionError, match="Connector is closed"):
await task


async def test_multiple_dns_resolution_requests_success(
make_client_request: _RequestMaker,
) -> None:
Expand Down
Loading