Skip to content

Probe seeded non-mDNS API devices once to verify live identity - #3071

Open
Hasan Khalil (gongloo) wants to merge 2 commits into
esphome:mainfrom
gongloo:fix/api-info-stale-identity-after-restart
Open

Hasan Khalil (gongloo) wants to merge 2 commits into
esphome:mainfrom
gongloo:fix/api-info-stale-identity-after-restart

Conversation

@gongloo

@gongloo Hasan Khalil (gongloo) commented Nov 14, 2026 •

Copy link
Copy Markdown

What does this implement/fix?

On restart, mac_address and deployed_version are seeded from the sidecar store while runtime_state.deployed_identity_live starts False. When an api: device comes online via ping or MQTT without mDNS discovery (priority_for != ReachabilitySource.MDNS), ApiInfoSource._is_due previously skipped probing because both fields were already populated, leaving deployed_identity_live permanently False and keeping the UI gated on "Waiting for mDNS discovery…".

  • Include not runtime.deployed_identity_live in ApiInfoSource._is_due's non-mDNS branch so online ping/MQTT-owned api: devices probe once per session to stamp deployed_identity_live=True.
  • In ApiInfoSource._fetch, avoid recording a failure cooldown when a connected probe stamps deployed_identity_live=True on an already-seeded device and nothing remains due.
  • Update the systemic-failure warning text ("MAC/version may stay blank or unverified") since ping/MQTT-owned seeded devices whose API probe cannot succeed now retry every failure cooldown (600s) and count toward that warning.
  • Add regression tests covering both successful verification (PING/MQTT) and cooldown backoff when a connected probe returns no identity, and align existing unit tests whose fixtures assumed both fields populated implied live/mDNS-owned identity.

Related issue or feature (if applicable):

  • None

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.

@github-actions github-actions Bot added the bugfix Bug fix label Nov 14, 2026
@codspeed

codspeed Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 1 benchmark is dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 28 untouched benchmarks
⏩ 1 skipped benchmark1


Comparing gongloo:fix/api-info-stale-identity-after-restart (4365047) with main (50fc28c)2

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

  2. No successful run was found on main (39adcc2) during the generation of this report, so 50fc28c was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@codecov

codecov Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.77%. Comparing base (27b50f9) to head (4365047).
⚠️ Report is 22 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##             main    #3071    +/-   ##
========================================
  Coverage   99.77%   99.77%            
========================================
  Files         300      305     +5     
  Lines       26564    27006   +442     
========================================
+ Hits        26503    26945   +442     
  Misses         61       61            
Flag Coverage Δ
py3.12 99.73% <100.00%> (+<0.01%) ⬆️
py3.14 99.62% <100.00%> (+<0.01%) ⬆️

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

Files with missing lines Coverage Δ
...lder/controllers/_device_state_monitor/api_info.py 100.00% <100.00%> (ø)

... and 9 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.

@esphbot

Copy link
Copy Markdown
Contributor

PR Review — Probe seeded non-mDNS API devices once to verify live identity

Correct, well-scoped fix for seeded ping/MQTT api: devices getting stuck on "Waiting for mDNS discovery…"; merge-ready, with three non-blocking suggestions.

What works well: the new not runtime.deployed_identity_live check sits inside the existing mDNS-ownership guard. That fits how the monitor already works, since apply_deployed_identity_live refuses the stamp while mDNS owns an api device and the release path hands the stamp back. The _fetch change re-runs _is_due to decide success versus miss, so a stamp that lands is not cooled down, while a refused stamp or leftover stale plaintext still is. The parametrized regression test covers both PING and MQTT and checks the stamp, the cooldown, and that the device is no longer selected. The test fixtures that relied on "both fields present means not due" were updated deliberately, by setting MDNS ownership or deployed_identity_live=True, rather than by weakening their assertions.

  • Ping/MQTT devices whose probe can never succeed are now re-probed every 600 s and count toward the systemic warning, whose text ("MAC/version may stay blank") is misleading for them.
  • The deployed_identity_live and not self._is_due(device) check in _fetch can be simplified to not self._is_due(device).
  • No test covers the case where a probe connects but returns no identity, so the device stays due and must still be cooled down.

🟢 Suggestions

1. Systemic-failure warning now counts devices that already have MAC/version, but its text says those may stay blank
esphome_device_builder/controllers/_device_state_monitor/api_info.py:328-343

What's wrong: _is_due is now true for any online, ping- or MQTT-owned api: device whose deployed_identity_live is false, even when MAC and version are already filled from the sidecar. Before this PR, those devices were never probed.

That changes what happens when the probe can never succeed, for example:

  • an encrypted device with no Noise key that resolves (a non-transient ProbeError)
  • a device whose API port is firewalled but still answers ping

Such a device stays due forever. It gets re-probed every _FAILURE_COOLDOWN (600 s), and _evaluate_systemic_health counts it as failing.

Why it matters: an MQTT- or ping-only fleet with 10 or more such devices will now trigger the WARNING "Native API info fallback is failing for %d devices; MAC/version may stay blank". Every one of those devices has MAC and version filled in, so the warning sends the operator looking for the wrong problem. Each also costs one worker-subprocess spawn every 10 minutes. That cost is bounded and intentional, but the PR description doesn't mention it.

How to fix (optional): reword the warning so it also covers unverified identity, e.g. "MAC/version may stay blank or unverified". Optionally add a sentence to the PR body noting that ping/MQTT devices whose probe can't succeed now retry every cooldown.

"Native API info fallback is failing for %d devices; MAC/version "
"may stay blank — check device API reachability, encryption keys, "
2. No test covers a connected probe that leaves the device due
tests/test_api_info_fallback.py:167-186

What's missing: the new parametrized test only covers the success path: the identity stamp lands and the device leaves cooldown. No test pins the opposite case, where a probe connects but returns an empty or identity-less payload (e.g. {"noise": False} with no mac/version) for a seeded ping-owned device.

Why it matters: in that case _fetch must still call _record_failure. Otherwise the device would be re-probed every sweep with no backoff, because it stays due. That is exactly the regression the new _fetch condition could introduce if someone later loosens it.

How to fix: add a short test that mocks _run_worker to return {"noise": False} and asserts that "kitchen" in src._cooldown and that deployed_identity_live is still False.


Checklist

  • No hardcoded secrets / injection / unsafe deserialization
  • Logic correctness of _is_due / _fetch cooldown handling
  • Error handling / backoff on persistent failures — suggestion #1
  • Untested branches introduced by the change — suggestion #2
  • PR description matches diff
  • Docstring/comment conventions (terse contracts)
  • No backward-incompatible API or persisted-state changes

Automated review by Kōan (Claude) HEAD=45b869f 58s

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

Tip

No blocking issues found — ready to merge.

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.

🟢 Approval recommended

No active review issues remain for the live-identity verification changes.

No open issues 🎉

What changed in this PR

This PR fixes live-identity verification for API devices whose metadata is restored after a dashboard restart but which come online through ping or MQTT rather than mDNS.

Changes:

  • Probe seeded, non-mDNS API devices until their live identity is verified.
  • Avoid a failure cooldown when a successful probe confirms existing metadata and clears the need to probe.
  • Add ping/MQTT regression coverage and update fixtures to distinguish populated metadata from verified identity.
File Description
tests/​test_mdns_cache_reconcile.py Makes mDNS ownership explicit in the cache-reconciliation test.
tests/​test_api_info_fallback.py Adds seeded-device verification coverage and updates identity fixtures.
esphome_device_builder/​controllers/​_device_state_monitor/​api_info.py Updates probe eligibility and successful-confirmation cooldown handling.

Review effort: Balanced (adaptive)

@gongloo

Copy link
Copy Markdown
Author

Thanks for the review! Both suggestions have been addressed in 4365047:

  1. Systemic warning & PR description: Reworded the log warning to "MAC/version may stay blank or unverified" and updated the PR description to note that ping/MQTT-owned seeded devices whose API probe cannot succeed retry on the failure cooldown.
  2. Empty-payload test: Added test_seeded_mdns_dark_device_cools_down_when_probe_returns_no_identity verifying that a connected probe returning {"noise": False} leaves deployed_identity_live false, keeps the device due, and records cooldown backoff.

(Note on the summary's _fetch simplification note: device.runtime_state.deployed_identity_live is intentionally kept alongside not self._is_due(device) because test_fetch_noise_session_confirms_encryption[mdns_owned] expects _record_failure when mDNS owns the device — _is_due is false under mDNS ownership while the stamp is refused.)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I'm also affected by this issue. PR looks good to me! Let's wait for maintainer to look into it.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bugfix Bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants