Skip to content

Rehome the sweep-loop base and adopt it in PingSource - #2035

Merged
J. Nick Koston (bdraco) merged 3 commits into
mainfrom
rehome-sweep-source-adopt-ping
Jul 14, 2026
Merged

J. Nick Koston (bdraco) merged 3 commits into
mainfrom
rehome-sweep-source-adopt-ping

Conversation

@bdraco

Copy link
Copy Markdown
Member

What does this implement/fix?

PR #2014 extracted the presence gated sweep loop into _api_probe.py, where ApiInfoSource and ApiReviverSource run on it while PingSource still hand rolled the identical loop. This moves the loop base to a neutral _sweep_source.py (SweepSource), keeps the budgeted worker dial and its _run_worker test seam in _api_probe.py as a thin ApiSweepSource(SweepSource) layer, and migrates PingSource onto the base. The privilege probe made _prepare async on the base; ping's resolve gather step keeps its bespoke exception handling inside its _sweep. Interval and bootstrap delay are now class attrs on the base, so the ping test seams patch PingSource._bootstrap_delay / _interval like the API sources already did.

One behavior change worth naming: the ping sweep body now gets the template's crash continue, so a raising _ping_sweep logs and retries next interval instead of killing the loop task for the process lifetime; a new test pins it. Cancellation still propagates.

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.

@github-actions github-actions Bot added the refactor Code refactor with no user-visible behaviour change label Jul 14, 2026
@bdraco

Copy link
Copy Markdown
Member Author

ESPHome Bot (@esphbot) review

@bdraco
J. Nick Koston (bdraco) marked this pull request as ready for review July 14, 2026 00:27
Copilot AI review requested due to automatic review settings July 14, 2026 00:27
@codspeed

codspeed Bot commented Jul 14, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 27 untouched benchmarks
⏩ 1 skipped benchmark1


Comparing rehome-sweep-source-adopt-ping (2a34644) with main (3ac9d41)

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

@codecov

codecov Bot commented Jul 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.60%. Comparing base (3ac9d41) to head (2a34644).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2035      +/-   ##
==========================================
- Coverage   99.60%   99.60%   -0.01%     
==========================================
  Files         242      243       +1     
  Lines       19745    19740       -5     
==========================================
- Hits        19667    19662       -5     
  Misses         78       78              
Flag Coverage Δ
py3.12 99.57% <100.00%> (-0.01%) ⬇️
py3.14 99.60% <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%> (ø)
...controllers/_device_state_monitor/_sweep_source.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%> (ø)
..._builder/controllers/_device_state_monitor/ping.py 100.00% <100.00%> (ø)
...uilder/controllers/_device_state_monitor/shared.py 100.00% <ø> (ø)
🚀 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 refactors the device-state monitor’s “presence-gated fixed-interval sweep loop” into a shared SweepSource base, then adopts it in PingSource (and re-threads the Native API sources through an ApiSweepSource subclass) to remove duplicated loop plumbing and unify behavior like crash-continue.

Changes:

  • Introduce SweepSource as the shared presence-gated sweep-loop template, and adapt API probe plumbing to layer on top of it.
  • Migrate PingSource to inherit from SweepSource, moving interval/bootstrap timing to class attributes and keeping ping-specific sweep behavior intact.
  • Update/extend tests to patch the new class attributes and to pin the “sweep crash doesn’t kill the loop” behavior.

Reviewed changes

Copilot reviewed 13 out of 13 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
tests/test_subscriber_presence.py Updates documentation wording to reference the generic sweep interval contract.
tests/test_state_monitor_lifecycle.py Updates ping loop interval/bootstrap monkeypatching to target PingSource class attrs; adjusts wording around interval.
tests/test_probe_device_ping.py Updates ping loop interval/bootstrap monkeypatching to target PingSource class attrs; tweaks docstring wording.
tests/test_ping_loop_pause.py Switches monkeypatching from module constants to PingSource class attrs and adds a test pinning crash-continue behavior.
tests/test_api_reviver.py Updates reviver _prepare tests for async _prepare() after the sweep base change.
tests/test_api_info_fallback.py Switches interval patching to ApiInfoSource._interval and validates SweepSource base behavior.
tests/conftest.py Updates fixture docstring to reflect ICMP privilege probe moving into PingSource._prepare.
esphome_device_builder/controllers/_device_state_monitor/shared.py Updates comment wording to reference “sweep interval” rather than ping-specific constants.
esphome_device_builder/controllers/_device_state_monitor/ping.py Migrates PingSource onto SweepSource, moving bootstrap/interval to base attrs and keeping ping-specific sweep logic.
esphome_device_builder/controllers/_device_state_monitor/api_reviver.py Makes _prepare async to match the new sweep base contract.
esphome_device_builder/controllers/_device_state_monitor/api_info.py Makes _prepare async to match the new sweep base contract.
esphome_device_builder/controllers/_device_state_monitor/_sweep_source.py Adds the shared sweep-loop base (SweepSource) with presence gating, crash-continue, and idle-wake behavior.
esphome_device_builder/controllers/_device_state_monitor/_api_probe.py Rehomes the sweep-loop base dependency and narrows _api_probe.py to API worker-dial plumbing via ApiSweepSource(SweepSource).

@bdraco

Copy link
Copy Markdown
Member Author

ESPHome Bot (@esphbot) review

@esphbot

Copy link
Copy Markdown
Contributor

PR Review — Rehome the sweep-loop base and adopt it in PingSource

Clean, well-tested behavior-preserving refactor; extracts a neutral SweepSource base and adopts it in PingSource. Merge-ready with two non-blocking nits.

Strengths:

  • The extraction is faithful: base _interval=60 matches the old _PING_INTERVAL/_INTERVAL, all three concrete subclasses set _sweep_label/_bootstrap_delay, and removed module constants have no stale references (the surviving _PING_INTERVAL hits are in the unrelated MQTT monitor).
  • Cancellation semantics are preserved — _sweep re-raises non-Exception BaseException and the base's except Exception can't swallow CancelledError.
  • The one intentional behavior change (ping sweep crash-continue) is explicitly named in the description and pinned by a new test; the base contract tests were rehomed to test_sweep_source.py rather than duplicated.
  • _prepare async-ification is consistent across all three sources and the base awaits it.

Needs attention (nits only):

  • _sweep_label/_bootstrap_delay have no defaults; a future subclass forgetting _sweep_label would make the crash-continue logger itself raise. Current subclasses all set them.
  • refactor label undersells the documented ping crash-continue behavior change.

🟢 Suggestions

1. Consider safe defaults for `_sweep_label` / `_bootstrap_delay`
esphome_device_builder/controllers/_device_state_monitor/_sweep_source.py:18-24

run() reads self._bootstrap_delay (first await asyncio.sleep) and self._sweep_label (in the crash-continue _LOGGER.exception), but both are bare annotations with no default — only _interval has one.

All three concrete subclasses (PingSource, ApiInfoSource, ApiReviverSource) set both, so this is not a live bug. The failure mode for a future subclass that forgets is asymmetric though:

  • Missing _bootstrap_delay → AttributeError at task start, loud and immediate. Acceptable.
  • Missing _sweep_label → the failure only surfaces when a sweep raises, and then the _LOGGER.exception("%s sweep failed", self._sweep_label) line itself raises AttributeError while handling the original exception, masking it.

Since the base already exists to be subclassed, giving _bootstrap_delay: float = 0 and _sweep_label = "sweep" defaults would harden the crash-continue path Copilot flagged, at zero cost to the current subclasses. Non-blocking.

    _sweep_label: str
    _bootstrap_delay: float
    _interval: float = 60
2. `refactor` label vs. the documented behavior change
esphome_device_builder/controllers/_device_state_monitor/ping.py:48

The PR is labeled Refactor (no behaviour change), but the description itself names one: the ping sweep now inherits the base's crash-continue, so a raising _ping_sweep logs-and-retries instead of killing the loop for the process lifetime (pinned by test_ping_loop_survives_a_raising_ping_sweep).

That is a genuine, intentional behavior change on the ping path — release-drafter slots the changelog off the label, so enhancement (or bugfix, since a dead ping loop is a latent defect) would describe it more accurately than refactor. Purely a process/changelog nit; the code is correct either way.


Checklist

  • Behavior-preserving refactor (aside from the documented crash-continue change)
  • Cancellation propagates through the new loop base
  • No stale references to removed constants
  • Base class robust against subclass misconfiguration — suggestion #1
  • PR label matches the change — suggestion #2
  • New/changed code covered by tests

Automated review by Kōan (Claude) HEAD=2a34644 2 min 51s

@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 152c18d into main Jul 14, 2026
21 checks passed
@bdraco
J. Nick Koston (bdraco) deleted the rehome-sweep-source-adopt-ping branch July 14, 2026 00:38
@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

refactor Code refactor with no user-visible behaviour change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Migrate PingSource onto the shared sweep-loop base and rehome it

3 participants