Skip to content

Revive stuck-offline devices from the persisted IP after identity verification - #2014

Merged
J. Nick Koston (bdraco) merged 14 commits into
mainfrom
api-reviver-persisted-ip
Jul 13, 2026
Merged

J. Nick Koston (bdraco) merged 14 commits into
mainfrom
api-reviver-persisted-ip

Conversation

@bdraco

Copy link
Copy Markdown
Member

What does this implement/fix?

When a device's mDNS responder goes quiet and the dashboard then restarts, the device shows offline forever unless the user adds manual_ip. The ping sweep has no target: the .local name won't resolve inside a container, the zeroconf cache is empty, and the restart wiped the RAM address list. The last known IPv4 is already persisted on disk for the OTA address cache, but no reachability path consults it.

This adds a last resort reviver for api: devices. A bare ICMP reply at a wall clock old DHCP address is never trusted as online evidence, since whatever now holds the lease would answer (the #1776 latch class). Instead ICMP acts only as a negative filter; when something answers, one short lived Native API device_info round trip confirms the responder's identity (name match required, MAC corroborating when both sides know it). On a match the device comes back online under the ping source and the ordinary sweep owns liveness and demotion from then on. On a name mismatch the persisted IP is proven stale and cleared, so neither the reviver nor the OTA cache trusts it again.

API connects occupy one of the ESP's scarce connection slots, so dials are strictly bounded: only devices with no other reachability signal are eligible, dials are serial and capped at 3 per sweep with exponential backoff on failure, and a process lifetime verified cache means a device is dialed at most once per stuck episode. Deployments without ICMP are deliberately not repaired, because the negative filter can't run and a verify only online could never demote.

MQTT devices already revive via the broker; web_server only and OTA only devices have no strong identity channel and keep today's behavior.

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

Copy link
Copy Markdown
Member Author

ESPHome Bot (@esphbot) review

@esphbot

ESPHome Bot (esphbot) commented Jul 13, 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.

No blocking issues found.

@bdraco

Copy link
Copy Markdown
Member Author

ESPHome Bot (@esphbot) review

@codspeed

codspeed Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 27 untouched benchmarks
⏩ 1 skipped benchmark1


Comparing api-reviver-persisted-ip (14e0b75) with main (eb13638)

Open in CodSpeed

Footnotes

  1. 1 benchmark was skipped, so the baseline result was used instead. If it was deleted from the codebase, click here and archive it to remove it from the performance reports. ↩

@bdraco

Copy link
Copy Markdown
Member Author

Good catch on the long-uptime window. The verified cache now stores a monotonic timestamp per pair and the dial-free fast path only honors it within a 6h TTL (68f1085); past that the next revival pays one fresh device_info dial and re-stamps, so a lease reassigned during a long silent gap has to pass identity verification again. Test added for the stale-pair re-dial.

ESPHome Bot (@esphbot) review

@esphbot

ESPHome Bot (esphbot) commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

@bdraco
J. Nick Koston (bdraco) marked this pull request as ready for review July 13, 2026 21:44
Copilot AI review requested due to automatic review settings July 13, 2026 21:44

@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.

@esphbot

Copy link
Copy Markdown
Contributor

J. Nick Koston (@bdraco): Good catch on the long-uptime window. The verified cache now stores a monotonic timestamp per pair a...

Confirmed resolved. _VERIFIED_TTL 6h bounds the dial-free path; stale pair re-dials and re-stamps. test_stale_verification_re_dials pins it.

One remaining branch: empty reported name invalidates the persisted IP. info.get("name", "") collapses absent/empty name to "", hits the mismatch path, clears the device's only revival lead. Guard: if not reported: record_dial_failure; return before the mismatch check. Encrypted cohort especially — successful handshake already proves identity.

@esphbot

ESPHome Bot (esphbot) commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Previous review — superseded by a newer review below.

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

Adds an identity-verified “last resort” reachability path to revive API-enabled devices that become permanently offline after a dashboard restart when mDNS and .local DNS resolution are unavailable, by using the persisted last-known IP as a lead (ICMP pre-filter + short-lived Native API device_info verification).

Changes:

  • Introduces ApiReviverSource plus shared Native-API probe plumbing (_api_probe.py) to verify identity and safely re-seed ping targets from persisted IPs.
  • Refactors ApiInfoSource to reuse the shared probe/loop base and extends the api_device_info worker to include the device name.
  • Wires persisted-IP invalidation through the devices controller + adds a comprehensive test suite covering revival, mismatch invalidation, and backoff/caps.

Reviewed changes

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

Show a summary per file
File Description
tests/test_state_monitor_lifecycle.py Extends lifecycle test to cover reviver task teardown.
tests/test_api_reviver.py New unit tests for persisted-IP revival behavior, gating, and backoff.
tests/test_api_info_fallback.py Updates tests for shared _api_probe refactor and name-inclusive worker output.
tests/controllers/devices/test_branches_coverage.py Adds branch coverage for persisted-IP invalidation callback behavior.
tests/conftest.py Adds callback + helper fixture for “stuck offline” device cohort setup.
esphome_device_builder/helpers/api_device_info.py Worker now returns name along with MAC/version.
esphome_device_builder/controllers/devices/state_callbacks.py Adds callback to clear stale persisted IP on verified mismatch.
esphome_device_builder/controllers/devices/controller.py Wires new persisted-IP invalidation callback from the monitor.
esphome_device_builder/controllers/_device_state_monitor/shared.py Adds shared ICMP concurrency constant + reachability helper.
esphome_device_builder/controllers/_device_state_monitor/ping.py Exposes ping_once() for reuse and shares ICMP concurrency limit.
esphome_device_builder/controllers/_device_state_monitor/controller.py Starts/stops the reviver loop and adds invalidation API surface.
esphome_device_builder/controllers/_device_state_monitor/api_reviver.py New persisted-IP identity-verified revival source implementation.
esphome_device_builder/controllers/_device_state_monitor/api_info.py Refactors to reuse shared probe plumbing; behavior stays “info-only”.
esphome_device_builder/controllers/_device_state_monitor/_api_probe.py New shared subprocess/probe helpers + presence-gated sweep base class.
docs/ARCHITECTURE.md Documents the new persisted-IP revival reachability path.
CLAUDE.md Adds repo-internal guidance about persisted-IP revival constraints/behavior.

@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.

  • Empty reported name is treated as a mismatch and clears the only revival lead

@bdraco

Copy link
Copy Markdown
Member Author

Addressed the important finding in 1d365be: an empty or absent reported name is now treated as an inconclusive dial, it records a dial failure and backs off instead of invalidating the only revival lead; test added. The resolver suggestion landed one commit earlier as ProbeRequestError, the reviver gives a transient resolve blip the short 600s retry while the definitive no-key case keeps the 1h hold; api_info keeps its single cooldown for both.

Also in this push from a /simplify pass: _prune handles duplicate-named YAML siblings via name buckets, the sweep loop and worker seam live once on ApiSweepSource, ping's DNS-failure branch and the reviver's cohort gate now share one address_resolution_exhausted predicate, and the persisted-IP invalidation flows through the constructor callback directly instead of a public forwarder. Follow-ups filed as #2020 and #2021.

ESPHome Bot (@esphbot) review

@bdraco

Copy link
Copy Markdown
Member Author

ESPHome Bot (@esphbot) review

@esphbot

Copy link
Copy Markdown
Contributor

J. Nick Koston (@bdraco): Addressed the important finding in 1d365be: an empty or absent reported name is now treated as an i...

Verified both. Empty-name guard present and tested. ProbeRequestError splits transient (600s) from no-key (1h). _prune name-bucketing confirmed against the duplicate-sibling test. Remaining nit: mismatch branch records no cooldown itself, relies on the wired invalidation callback to drop the IP. Non-blocking.

@esphbot

ESPHome Bot (esphbot) commented Jul 13, 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.

No blocking issues found.

@bdraco

Copy link
Copy Markdown
Member Author

Applied in 2d42795. run_worker now classifies outcomes: a worker that completed its protocol and reported the device's refusal returns None (escalating backoff), while host-side misses (spawn failure, subprocess timeout, no parseable payload) raise the transient error and get the short retry, so a local glitch never feeds a device's 6h backoff. The exception is now ProbeError since it covers the whole dial, not just request building.

Also in this push from the round-3 /simplify: a monitor-wide Semaphore(1) bounds concurrent worker subprocesses across both API sources; the crash-logging done-callback lives once in helpers.async_ (the mDNS interface monitor adopts it); ping's redundant cached-local branch collapsed into the shared no-target predicate (one cache walk instead of two); the reviver prunes through the monitor's name index instead of hand-built buckets; and cooldown keys are bound before the invalidation callback can clear the IP they need.

ESPHome Bot (@esphbot) review

@bdraco

Copy link
Copy Markdown
Member Author

ESPHome Bot (@esphbot) review

@esphbot

Copy link
Copy Markdown
Contributor

J. Nick Koston (@bdraco): Applied in 2d42795. run_worker now classifies outcomes: a worker that completed its protocol and re...

Confirmed. run_worker now returns None only for device-side refusal (escalating backoff); spawn/timeout/parse misses raise transient ProbeError → short cooldown. Prior 6h-backoff-on-local-glitch concern resolved. Shared Semaphore(1) bounds both sources correctly. One residual nit: empty reported-name branch backs off without a log line, unlike the mismatch/MAC-conflict branches — a debug line would make an identity-blank responder diagnosable.

@esphbot

ESPHome Bot (esphbot) commented Jul 13, 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.

No blocking issues found.

@bdraco

Copy link
Copy Markdown
Member Author

Added in the latest push: the identity-blank verdict now logs at debug like its sibling branches, so a responder that connects but never reports a name is visible while it escalates.

ESPHome Bot (@esphbot) review

@esphbot

Copy link
Copy Markdown
Contributor

J. Nick Koston (@bdraco): Added in the latest push: the identity-blank verdict now logs at debug like its sibling branches, so...

Confirmed at 9ee3f0e. Identity-blank branch now logs debug before backoff, matching the mismatch and MAC-conflict verdicts. Verified it is the only change since the reviewed head. Remaining gather nit is benign: ping_once catches ICMPLibError/OSError and returns None, so the pre-filter batch cannot abort. Merge-ready.

@esphbot

ESPHome Bot (esphbot) commented Jul 13, 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.

No blocking issues found.

@codecov

codecov Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.60%. Comparing base (b1b6427) to head (14e0b75).
⚠️ Report is 11 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2014      +/-   ##
==========================================
+ Coverage   99.58%   99.60%   +0.01%     
==========================================
  Files         239      242       +3     
  Lines       19532    19745     +213     
==========================================
+ Hits        19451    19667     +216     
+ Misses         81       78       -3     
Flag Coverage Δ
py3.12 99.57% <100.00%> (+0.01%) ⬆️
py3.14 99.59% <100.00%> (+0.01%) ⬆️

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

Files with missing lines Coverage Δ
...er/controllers/_device_state_monitor/_api_probe.py 100.00% <100.00%> (ø)
...lder/controllers/_device_state_monitor/api_info.py 100.00% <100.00%> (ø)
...r/controllers/_device_state_monitor/api_reviver.py 100.00% <100.00%> (ø)
...er/controllers/_device_state_monitor/controller.py 98.55% <100.00%> (ø)
..._builder/controllers/_device_state_monitor/mdns.py 99.57% <100.00%> (-0.01%) ⬇️
..._builder/controllers/_device_state_monitor/ping.py 100.00% <100.00%> (ø)
...uilder/controllers/_device_state_monitor/shared.py 100.00% <100.00%> (ø)
...e_device_builder/controllers/devices/controller.py 99.73% <100.00%> (+<0.01%) ⬆️
...ice_builder/controllers/devices/state_callbacks.py 100.00% <100.00%> (ø)
esphome_device_builder/helpers/api_device_info.py 100.00% <100.00%> (ø)
... and 2 more

... and 3 files with indirect coverage changes

🚀 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

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

Comment thread tests/test_api_reviver.py Resolved
@bdraco

Copy link
Copy Markdown
Member Author

ESPHome Bot (@esphbot) review

@esphbot

ESPHome Bot (esphbot) commented Jul 13, 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.

No blocking issues found.

@bdraco

Copy link
Copy Markdown
Member Author

ESPHome Bot (@esphbot) review

@esphbot

ESPHome Bot (esphbot) commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

PR Review — Revive stuck-offline devices from the persisted IP after identity verification

Merge-ready. Identity-gated persisted-IP revival that closes the #1776 stale-lease latch class, with thorough tests and docs in the same change. No blocking issues; prior-round findings all resolved.

Specific strengths:

  • ICMP stays a pure negative pre-filter; ONLINE is claimed only after a Native API name match (MAC corroborating when both sides know it), with a _VERIFIED_TTL-bounded dial-free fast path that re-verifies past expiry — a re-leased IP can't ride a stale verification back to ONLINE.

  • _sweep binds each candidate's (device, ip) pair once and re-checks device.ip after every await, so a mid-sweep mDNS re-learn or invalidation callback can't misapply the echo (pinned by test_pair_mutated_between_prefilter_and_dial_is_skipped / test_mid_dial_mdns_address_set_is_not_overwritten).

  • Bounded resource use throughout: per-sweep dial cap, escalating backoff, monitor-wide Semaphore(1) shared with api_info, shared global ICMP concurrency, and name-bucketed _prune that survives duplicate-name YAMLs with distinct persisted IPs.

  • The _api_probe.py/CooldownLedger extraction cleanly deduplicates the sweep-loop/worker plumbing between api_info and the reviver; host-side vs device-side worker failures are correctly classified so a spawn/timeout blip doesn't feed the device's escalating backoff. stop() now cancels loop tasks eagerly before cancel_browser so a mid-sweep loop can't spawn new work during teardown.

  • No new issues found on this pass; the shared-ICMP-budget, task-drain refactor, and name-inclusive worker payload are all internally consistent and covered by tests.



Checklist


Silent Failure Analysis

🟡 **MEDIUM** — unisolated gather / partial silent no-op
esphome_device_builder/controllers/_device_state_monitor/api_reviver.py:165-170

Risk: Unlike the ping sweep's gather (which passes return_exceptions=True to isolate per-device failures), one unexpected exception from any _prefilter aborts the whole cohort's revival for that sweep, so silent devices are neither cooled down nor retried consistently and the failure is only surfaced by the loop's generic handler.

rtts = await asyncio.gather(*(self._prefilter(device, ip) for device, ip in pairs))
now = time.monotonic()
dials = 0
for (device, ip), rtt in zip(pairs, rtts, strict=True):

Fix: Pass return_exceptions=True to gather and treat an exceptional result as a prefilter miss (skip/cool that pair) so one device's error can't drop the entire cohort, mirroring PingSource._ping_sweep.


Automated review by Kōan (Claude) HEAD=14e0b75 37s

@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 3ac9d41 into main Jul 13, 2026
21 checks passed
@bdraco
J. Nick Koston (bdraco) deleted the api-reviver-persisted-ip branch July 13, 2026 23:57
@github-actions github-actions Bot locked and limited conversation to collaborators Jul 15, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

bugfix Bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants