Skip to content

Handle aiodns pycares exceptions "leaking"#170048

Closed
gjohansson-ST wants to merge 8 commits into
devfrom
gj-20260507-02
Closed

Handle aiodns pycares exceptions "leaking"#170048
gjohansson-ST wants to merge 8 commits into
devfrom
gj-20260507-02

Conversation

@gjohansson-ST
Copy link
Copy Markdown
Member

Breaking change

Proposed change

Background: aio-libs/aiodns#231
pycares exceptions leaks through and raises so until addressed we need to catch Exception

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New integration (thank you!)
  • New feature (which adds functionality to an existing integration)
  • Deprecation (breaking change to happen in the future)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Additional information

  • This PR fixes or closes issue: fixes #
  • This PR is related to issue:
  • Link to documentation pull request:
  • Link to developer documentation pull request:
  • Link to frontend pull request:

Checklist

  • I understand the code I am submitting and can explain how it works.
  • The code change is tested and works locally.
  • Local tests pass. Your PR cannot be merged unless tests pass
  • There is no commented out code in this PR.
  • I have followed the [development checklist][dev-checklist]
  • I have followed the [perfect PR recommendations][perfect-pr]
  • The code has been formatted using Ruff (ruff format homeassistant tests)
  • Tests have been added to verify that the new code works.
  • Any generated code has been carefully reviewed for correctness and compliance with project standards.

If user exposed functionality or configuration variables are added/changed:

  • Documentation added/updated for [www.home-assistant.io][docs-repository]

If the code communicates with devices, web services, or third-party tools:

  • The [manifest file][manifest-docs] has all fields filled out correctly.
    Updated and included derived files by running: python3 -m script.hassfest.
  • New or updated dependencies have been added to requirements_all.txt.
    Updated by running python3 -m script.gen_requirements_all.
  • For the updated dependencies a diff between library versions and ideally a link to the changelog/release notes is added to the PR description.

To help with the load of incoming pull requests:

  • I have reviewed two other [open pull requests][prs] in this repository.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR updates the dnsip integration to prevent unexpected pycares exceptions (raised via aiodns) from bubbling up and crashing hostname resolution / validation.

Changes:

  • Broadened exception handling in the DNS IP sensor update loop to catch non-DNSError failures.
  • Broadened exception suppression in the config flow hostname validation checks to tolerate additional resolver exceptions.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 4 comments.

File Description
homeassistant/components/dnsip/sensor.py Catch broader resolver exceptions during periodic DNS queries to avoid update crashes.
homeassistant/components/dnsip/config_flow.py Suppress broader resolver exceptions during config-flow validation to avoid flow failures from pycares leaks.

Comment thread homeassistant/components/dnsip/sensor.py Outdated
Comment thread homeassistant/components/dnsip/config_flow.py Outdated
Comment thread homeassistant/components/dnsip/config_flow.py Outdated
Comment on lines 125 to 128
except Exception as err: # noqa: BLE001
# Handle leaking through other (pycares) exceptions than DNSError
_LOGGER.warning("Exception while resolving host: %s", err)
await self.resolver.close()
@frenck frenck modified the milestones: 2026.5.1, 2026.5.2 May 8, 2026
Copilot AI review requested due to automatic review settings May 10, 2026 13:57
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated 5 comments.

_LOGGER.debug("Timeout while resolving host: %s", err)
await self.resolver.close()
except DNSError as err:
except (aiodns.error.DNSError, AresError, asyncio.CancelledError) as err:
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

That's completely opposite of what we want

Comment on lines 74 to +85
tasks = await asyncio.gather(
async_check(hostname, resolver_ipv4, "A", port=port),
async_check(hostname, resolver_ipv6, "AAAA", port=port_ipv6),
async_check(hostname, resolver_ipv4, "AAAA", port=port),
return_exceptions=True,
)

result[CONF_IPV4] = tasks[0]
result[CONF_IPV6] = tasks[1]
result[CONF_IPV6_V4] = tasks[2]
result[CONF_IPV4] = bool(tasks[0]) if not isinstance(tasks[0], Exception) else False
result[CONF_IPV6] = bool(tasks[1]) if not isinstance(tasks[1], Exception) else False
result[CONF_IPV6_V4] = (
bool(tasks[2]) if not isinstance(tasks[2], Exception) else False
)
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Same here

Comment thread homeassistant/components/dnsip/config_flow.py Outdated
Comment thread homeassistant/components/dnsip/config_flow.py Outdated
Comment thread homeassistant/components/dnsip/sensor.py
Copilot AI review requested due to automatic review settings May 10, 2026 14:08
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 3 out of 3 changed files in this pull request and generated 4 comments.

Comment thread homeassistant/components/dnsip/config_flow.py
Comment on lines 119 to 122
async with asyncio.timeout(10):
if self.resolver._closed: # noqa: SLF001
self.create_dns_resolver()
response = await self.resolver.query(self.hostname, self.querytype)
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Is for a separate PR

Comment thread homeassistant/components/dnsip/sensor.py
Comment thread tests/components/dnsip/test_config_flow.py Outdated
Copy link
Copy Markdown
Member

@frenck frenck left a comment

Choose a reason for hiding this comment

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

A few issues that should be addressed before merging.

The main concern is around asyncio.CancelledError handling: catching it without re-raising will swallow task cancellation and can prevent Home Assistant from shutting down or reloading cleanly. There is also a subtle type hierarchy issue with the isinstance check in the config flow on Python 3.14.

await self.resolver.close()
if self.resolver:
await self.resolver.close()
except (aiodns.error.DNSError, AresError, asyncio.CancelledError) as err:
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.

Catching asyncio.CancelledError without re-raising it will swallow task cancellation. When Home Assistant is shutting down or reloading, the update task may be cancelled, and if CancelledError is caught and silenced here, the shutdown/reload can hang (until the 10 second timeout fires).

Suggestion: handle CancelledError separately and re-raise it after cleanup, or remove it from this except clause entirely:

except asyncio.CancelledError:
    if self.resolver:
        await self.resolver.close()
    raise
except (aiodns.error.DNSError, AresError) as err:
    _LOGGER.debug("Exception while resolving host: %s", err)
    if self.resolver:
        await self.resolver.close()

result[CONF_IPV4] = tasks[0]
result[CONF_IPV6] = tasks[1]
result[CONF_IPV6_V4] = tasks[2]
result[CONF_IPV4] = bool(tasks[0]) if not isinstance(tasks[0], Exception) else False
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.

In Python 3.14, asyncio.CancelledError inherits from BaseException, not Exception. With return_exceptions=True, if a task gets cancelled, the CancelledError instance is returned as a result. Then isinstance(tasks[0], Exception) returns False, and bool(CancelledError()) evaluates to True, making it look like DNS resolution succeeded when it was actually cancelled.

Consider using BaseException instead:

result[CONF_IPV4] = bool(tasks[0]) if not isinstance(tasks[0], BaseException) else False

Or check for the expected success type directly:

result[CONF_IPV4] = isinstance(tasks[0], list) and bool(tasks[0])

if self.resolver:
await self.resolver.close()
except (aiodns.error.DNSError, AresError, asyncio.CancelledError) as err:
_LOGGER.debug("Exception while resolving host: %s", err)
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.

This changed from _LOGGER.warning to _LOGGER.debug. Legitimate persistent DNS errors will no longer be visible to users at the default log level. Was this intentional? Since the entity will go unavailable after retries are exhausted that might be sufficient as a signal, but worth confirming.

@home-assistant
Copy link
Copy Markdown
Contributor

Please take a look at the requested changes, and use the Ready for review button when you are done, thanks 👍

Learn more about our pull request process.

@home-assistant home-assistant Bot marked this pull request as draft May 15, 2026 19:20
@bdraco
Copy link
Copy Markdown
Member

bdraco commented May 16, 2026

aio-libs/aiodns#245

@bdraco bdraco mentioned this pull request May 16, 2026
21 tasks
bdraco added a commit to bdraco/home-assistant that referenced this pull request May 16, 2026
@github-actions github-actions Bot locked and limited conversation to collaborators May 17, 2026
@frenck frenck removed this from the 2026.5.3 milestone May 17, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants