Skip to content

Reconcile zeroconf sockets when network interfaces change - #1770

Merged
J. Nick Koston (bdraco) merged 3 commits into
mainfrom
zeroconf-update-interfaces
Jun 30, 2026
Merged

J. Nick Koston (bdraco) merged 3 commits into
mainfrom
zeroconf-update-interfaces

Conversation

@bdraco

Copy link
Copy Markdown
Member

What does this implement/fix?

python-zeroconf binds its sockets once at construction, so it never notices interfaces that come or go afterward (a VPN connecting, Wi-Fi reconnecting, a Docker network attaching); mDNS discovery then silently goes deaf on the changed interface until the process restarts. python-zeroconf 0.150.0 added async_update_interfaces, which rescans the host and reconciles the sockets in use (binds responders for interfaces that appeared, tears down ones that went away, re-announces existing registrations).

This wires that in with a small interface monitor that snapshots the host addresses on a relaxed timer and calls async_update_interfaces only when the set actually changes; a no-op tick touches nothing. MdnsSource owns the task; it comes up with the responder and is cancelled, then awaited, before zeroconf closes so it can never reconcile a closing instance or leak past shutdown. ifaddr.get_adapters() is blocking, so every snapshot runs in an executor and the event loop only awaits. Detection is the portable poll the zeroconf docs recommend when no netlink or framework push signal is wired, so it works on the Windows CI matrix too.

Related issue or feature (if applicable):

Types of changes

  • Bugfix (non-breaking change which fixes an issue) — bugfix
  • New feature (non-breaking change which adds functionality) — new-feature
  • Enhancement to an existing feature — enhancement
  • Breaking change (fix or feature that would cause existing functionality to not work as expected) — breaking-change
  • Refactor (no behaviour change) — refactor
  • Documentation only — docs
  • Maintenance / chore — maintenance
  • CI / workflow change — ci
  • Dependencies bump — dependencies

Frontend coordination

  • No frontend change needed
  • Companion frontend PR: esphome/device-builder-frontend#

Checklist

  • The code change is tested and works locally.
  • Pre-commit hooks pass (ruff, codespell, yaml/json/python checks).
  • Tests have been added or updated under tests/ where applicable.
  • components.index.json / definitions/components/*.json have not been hand-edited (regenerate via script/sync_components.py if a sync is needed).
  • Architecture-level changes are reflected in docs/ARCHITECTURE.md and/or docs/API.md.

@bdraco J. Nick Koston (bdraco) added the enhancement Improvement to an existing feature label Jun 30, 2026
@bdraco
J. Nick Koston (bdraco) marked this pull request as ready for review June 30, 2026 20:54
Copilot AI review requested due to automatic review settings June 30, 2026 20:54
@codspeed

codspeed Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 27 untouched benchmarks


Comparing zeroconf-update-interfaces (72f8d5a) with main (2aa7863)

Open in CodSpeed

@codecov

codecov Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.55%. Comparing base (2aa7863) to head (72f8d5a).

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff           @@
##             main    #1770   +/-   ##
=======================================
  Coverage   99.55%   99.55%           
=======================================
  Files         229      230    +1     
  Lines       18291    18345   +54     
=======================================
+ Hits        18209    18263   +54     
  Misses         82       82           
Flag Coverage Δ
py3.12 99.52% <100.00%> (+<0.01%) ⬆️
py3.14 99.55% <100.00%> (+<0.01%) ⬆️

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

Files with missing lines Coverage Δ
...rollers/_device_state_monitor/interface_monitor.py 100.00% <100.00%> (ø)
..._builder/controllers/_device_state_monitor/mdns.py 99.43% <100.00%> (+0.07%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

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 improves mDNS resilience by detecting host network interface/address changes (e.g., VPN/Wi‑Fi/Docker churn) and triggering python-zeroconf’s interface reconciliation so discovery doesn’t go stale until restart.

Changes:

  • Add an ifaddr-based polling monitor that snapshots host addresses and calls AsyncEsphomeZeroconf.async_update_interfaces() only on change.
  • Wire the monitor into MdnsSource lifecycle so it starts with zeroconf and is cancelled before zeroconf shutdown.
  • Add unit tests covering reconcile/no-op behavior and lifecycle teardown.

Reviewed changes

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

File Description
esphome_device_builder/controllers/_device_state_monitor/mdns.py Spawns and cancels the interface-monitor task around zeroconf lifecycle.
esphome_device_builder/controllers/_device_state_monitor/interface_monitor.py New polling monitor that snapshots addresses and reconciles zeroconf sockets on change.
tests/test_interface_monitor.py New tests for reconcile triggering, no-op behavior, and retry semantics.
tests/test_state_monitor_lifecycle.py Adds a lifecycle test ensuring the interface-monitor task is spawned and torn down during stop.

@esphbot

ESPHome Bot (esphbot) commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@esphbot ESPHome Bot (esphbot) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Blocking issues found.

  • Snapshot executor calls are unguarded — a transient adapter-read error kills the monitor silently

@bdraco

Copy link
Copy Markdown
Member Author

Thanks, this was reviewed against the pre-fix commit 2785c73; the blocking item plus the follow-ups are all addressed now.

Blocking, snapshot executor calls unguarded (also the HIGH and the line 41 MEDIUM): fixed in c67d6e4. Both the pre-loop and in-loop snapshots now go through _safe_snapshot, which catches a raising get_adapters, logs, and returns None; a None tick is skipped (guarded so a transient error is not read as every interface vanishing), so one bad scan no longer kills the reconciler. Covered by test_snapshot_failure_does_not_kill_loop.

Fire-and-forget task with no failure surfacing (mdns.py MEDIUM): fixed in 72f8d5a. The task now gets a done-callback, _log_interface_monitor_exit, mirroring _log_api_info_task_exit; a cancelled task stays silent, an unexpected crash logs at error. Tests cover both the crash-logs and cancel-is-silent paths.

Dependency floor: added zeroconf>=0.150.0 to the base dependencies in 72f8d5a, with a comment; we import zeroconf directly and async_update_interfaces landed in 0.150.0, so this matches the existing explicit-pin pattern (ruamel.yaml, voluptuous) rather than relying on the transitive version.

Second adapter-polling loop: aligned the cadence to DashboardAdvertiser's _REFRESH_INTERVAL_SECONDS (300s) in 72f8d5a so the two loops share one interval. A full consolidation is a larger change; the advertiser re-announces the dashboard's own service on its addresses, while this reconciles zeroconf's listen/responder sockets, so they have distinct ownership and lifecycles. Happy to do that as a separate refactor if you think it is worth it.

@esphbot

Copy link
Copy Markdown
Contributor

J. Nick Koston (@bdraco): Thanks, this was reviewed against the pre-fix commit 2785c73; the blocking item plus the follow-ups ...

Re-reviewed at current HEAD. All items confirmed fixed. Verified the floor independently: async_update_interfaces lands in zeroconf 0.150.0 on AsyncZeroconf, absent in 0.149.x. No-arg call defaults to construction-time interfaces — comment accurate. Cadence matches _REFRESH_INTERVAL_SECONDS (300s). LGTM.

@esphbot

Copy link
Copy Markdown
Contributor

PR Review — Reconcile zeroconf sockets when network interfaces change

All prior blocking findings resolved and independently verified — merge-ready.

What's solid:

  • The core API is real: confirmed async_update_interfaces() exists in zeroconf 0.150.0 on AsyncZeroconf (parent of AsyncEsphomeZeroconf), and the no-arg call correctly defaults to the construction-time interface set. The explicit zeroconf>=0.150.0 floor is necessary (the method is absent in 0.149.x) and follows the existing explicit-pin pattern.
  • Shutdown ordering is deliberate and tested: the monitor is cancelled-and-awaited before async_close, so it can never reconcile a closing instance or leak past shutdown.
  • Blocking ifaddr.get_adapters() stays off the loop via run_in_executor; the frozenset snapshot makes change-detection order-independent; _ip_to_str keeps v6 %scope and drops flowinfo to avoid spurious churn.

Fixes since the prior review, all with regression tests:

  • _safe_snapshot now guards both the pre-loop and in-loop reads; a raising get_adapters logs and returns None (skipped, not read as every interface vanishing).

  • _log_interface_monitor_exit done-callback surfaces an unexpected crash while staying silent on cancel.

  • close_zeroconf swallows a non-cancellation error from a crashed monitor task so it can't abort shutdown before zeroconf closes.

  • Poll cadence aligned to DashboardAdvertiser's 300s.

  • No remaining blocking or warning-level issues.



Checklist

  • Error handling resilient in long-running loop
  • Task crashes surfaced (done-callback / logging)
  • Blocking I/O kept off event loop
  • Shutdown/lifecycle ordering correct, no leak
  • Dependency floor declared for new API
  • Test coverage for new branches
  • No hardcoded secrets / injection / path traversal

Automated review by Kōan (Claude) HEAD=72f8d5a 3 min 7s

@esphbot ESPHome Bot (esphbot) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

No blocking issues found.

@bdraco
J. Nick Koston (bdraco) merged commit 8deff7b into main Jun 30, 2026
20 checks passed
@bdraco
J. Nick Koston (bdraco) deleted the zeroconf-update-interfaces branch June 30, 2026 22:46
@github-actions github-actions Bot locked and limited conversation to collaborators Jul 2, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

enhancement Improvement to an existing feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants