5 Commits
Author SHA1 Message Date
rick 330642e6b9 Merge agent/defer-cold-start-backfill: v0.1.3 non-blocking cold-start
Defers per-record cold-start backfill out of async_setup's await chain
to remove the multi-minute config-entry freeze on installs with many
batteries. Adds one persistent notification when the initial backfill
batch completes; softens the v0.1.1 dialog warning. Ships brand/logo
assets alongside the v0.1.1 brand/icon assets. 115 tests passing.
2026-05-11 11:40:00 +02:00
rickandCursor 20ce139069 openspec(defer-cold-start-backfill): apply phase done; ready to merge
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 11:39:53 +02:00
rickandCursor 006771a5f2 v0.1.3: defer cold-start backfill so setup returns sub-second
The v0.1.1 dialog warned that setup could freeze for several minutes
on installs with many batteries. Root cause was _scan_initial_entities
in coordinator.py awaiting _attempt_cold_start_backfill for every
record in series, dispatching 1-2 recorder/LTS executor jobs each.
With the user's 70-battery install, ~140 serialized executor jobs
on the await chain of async_setup blocked config-entry setup for
several minutes.

This release defers cold-start backfill out of the await chain:

1. Per-record fire-and-forget. _ensure_record schedules
   _attempt_cold_start_backfill via hass.async_create_task instead of
   awaiting it. async_setup returns within the time bounded by the
   entity-registry scan, regardless of how many batteries need
   backfill or how slow the recorder is.

2. One persistent notification when the initial backfill batch
   finishes. The coordinator tracks in-flight backfills via
   _pending_backfills: set[str]; when the set transitions from
   non-empty to empty, exactly one persistent_notification fires
   with notification_id="battery_lifetime_cold_start_complete". No
   notification fires if no batteries needed backfill.

3. Softened config-dialog text. The bold/all-caps "WILL APPEAR
   FROZEN FOR SEVERAL MINUTES" warning is replaced with an accurate
   "background backfill may take several minutes; a notification
   will appear when complete" note.

Cold-start semantics (LTS-then-recorder fallback, qualifying-jump
rules, replacement event payload, persisted replaced_on) unchanged.
Live-vs-historical race handled by _attempt_cold_start_backfill's
existing replaced_on guard: live commits during background backfill
win.

Also ships brand/logo.png and brand/logo@2x.png (copies of the icon
assets) so HA's brands-proxy logo slot is populated alongside the
icon shipped in v0.1.1.

Tests: 3 new in tests/test_coordinator.py covering non-blocking
setup, exactly-once completion notification, and
no-pending-no-notification. Full suite 115 passed.

Modifies the coordinator-scheduling capability with two ADDED
requirements; spec sync happens at archive time.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 11:38:59 +02:00
rickandCursor 2e93800981 openspec(defer-cold-start-backfill): propose phase artifacts
Proposes deferring cold-start backfill out of the await chain of
async_setup so config-entry setup returns sub-second regardless of
how many batteries need historical replaced_on lookup. Adds a single
persistent notification when the initial backfill batch completes,
and softens the v0.1.1 all-caps freeze warning in the config dialog
to match the new background-backfill behaviour.

Modifies coordinator-scheduling capability with two new requirements
(non-blocking setup, exactly-once batch-completion notification).
No changes to replacement-detection contract.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 11:24:14 +02:00
rickandCursor ddc12ba6d3 openspec(optimize-coordinator-tick): archive + sync specs; HANDOFF v0.1.2
- Move openspec/changes/optimize-coordinator-tick to
  openspec/changes/archive/2026-05-09-optimize-coordinator-tick.
- Sync the change's coordinator-scheduling delta to
  openspec/specs/coordinator-scheduling/spec.md so future agents have
  the heartbeat / per-event publish contract in main specs.
- HANDOFF.md: bump current state to v0.1.2; mark the brands-PR task
  obsolete (HACS uses the local brand mechanism on HA 2026.3+, and
  home-assistant/brands auto-closes custom-integration PRs); note
  v0.1.2 did not touch the cold-start setup freeze in task #3.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-09 19:16:06 +02:00
21 changed files with 408 additions and 60 deletions
+20 -24
View File
@@ -1,11 +1,13 @@
# Agent Handoff — Battery Lifetime
## Current State (2026-05-08)
## Current State (2026-05-09)
The Battery Lifetime custom Home Assistant integration is working and deployed via HACS on the user's live install (70 battery-powered devices → 554 companion entities). Current release is **v0.1.1** on GitHub via HACS.
The Battery Lifetime custom Home Assistant integration is working and deployed via HACS on the user's live install (70 battery-powered devices → 554 companion entities). Current release is **v0.1.2** on GitHub via HACS.
The OpenSpec change `add-battery-lifetime` is at 56/62 tasks; the remaining six (10.2–10.7) are manual-validation gates against a real HA install. Some are implicitly being validated right now by the live install; see "What Needs Doing Next" below.
The OpenSpec change `optimize-coordinator-tick` (v0.1.2 release) is fully archived under `openspec/changes/archive/2026-05-09-optimize-coordinator-tick/`. Specs synced to `openspec/specs/coordinator-scheduling/spec.md`.
## What's Done
- Full implementation of the Battery Lifetime integration:
@@ -23,34 +25,21 @@ The OpenSpec change `add-battery-lifetime` is at 56/62 tasks; the remaining six
- HACS packaging (`hacs.json`, `info.md`, `README.md`, `LICENSE`, `manifest.json`).
- 107 unit tests passing under `pytest-homeassistant-custom-component`.
- v0.1.0 released and installed live on the user's HA install. v0.1.1 follow-up adds a bold/all-caps setup-time warning to the config dialog and ships icon assets in `custom_components/battery_lifetime/brand/` (256×256 + 512×512).
- Both `master` and tags `v0.1.0`/`v0.1.1` pushed to gitea (origin) and GitHub (github).
- README and OpenSpec specs aligned with the implementation; `replacement-detection/spec.md` enumerates the three stale-prior services explicitly.
- v0.1.2 ships three coordinator scheduling optimizations (drop redundant 10-minute timer, per-source-event O(1) update via `async_set_updated_data`, diff-gated heartbeat publish). 5 new tests in `tests/test_coordinator.py`, full suite 112 passed.
- Both `master` and tags `v0.1.0`/`v0.1.1`/`v0.1.2` pushed to gitea (origin) and GitHub (github).
- README and OpenSpec specs aligned with the implementation; `replacement-detection/spec.md` enumerates the three stale-prior services explicitly. `coordinator-scheduling/spec.md` documents the per-event vs heartbeat contracts.
## What Needs Doing Next (Immediate)
### 1. Brands PR for the HACS icon
### 1. ~~Brands PR for the HACS icon~~ — OBSOLETE as of HA 2026.3
HACS sources its integration icons from [home-assistant/brands](https://github.com/home-assistant/brands), not from the integration repo. The local assets at `custom_components/battery_lifetime/brand/icon.png` (256) and `icon@2x.png` (512) are ready to ship. To make HACS display them:
Home Assistant 2026.3 (announcement: <https://developers.home-assistant.io/blog/2026/02/24/brands-proxy-api>) introduced a local Brands Proxy API. Custom integrations now ship `brand/icon.png`, `brand/icon@2x.png` (and optionally `logo.png` / `dark_*.png`) inside their own repository, and HA serves them from `/api/brands/integration/<domain>/icon.png`. The `home-assistant/brands` repo **auto-closes** PRs for `custom_integrations/*` and tells contributors to use the inline mechanism (verified via closed PRs `home-assistant/brands#10149` and `#10230` cited in `hacs/integration#5223`).
```bash
GH_TOKEN=$(cat /home/rick/Lab/Dev/Hassio-PerfectDraftPro/.github-token) gh repo fork home-assistant/brands --clone --remote
cd brands
git checkout -b add-battery-lifetime
mkdir -p custom_integrations/battery_lifetime
cp /home/rick/Lab/Dev/Hassio-Battery-Lifetimes/custom_components/battery_lifetime/brand/icon.png custom_integrations/battery_lifetime/icon.png
cp /home/rick/Lab/Dev/Hassio-Battery-Lifetimes/custom_components/battery_lifetime/brand/icon@2x.png custom_integrations/battery_lifetime/icon@2x.png
# logo.png + logo@2x.png are usually required too — same image is fine for an icon-only brand
cp /home/rick/Lab/Dev/Hassio-Battery-Lifetimes/custom_components/battery_lifetime/brand/icon.png custom_integrations/battery_lifetime/logo.png
cp /home/rick/Lab/Dev/Hassio-Battery-Lifetimes/custom_components/battery_lifetime/brand/icon@2x.png custom_integrations/battery_lifetime/logo@2x.png
git add custom_integrations/battery_lifetime
git commit -m "Add battery_lifetime"
git push origin add-battery-lifetime
GH_TOKEN=... gh pr create --repo home-assistant/brands \
--title "Add battery_lifetime" \
--body "Custom integration: https://github.com/Falkvinge/hassio-integration-battery-lifetime"
```
We already ship `custom_components/battery_lifetime/brand/icon.png` (256×256) and `icon@2x.png` (512×512), so on the user's HA 2026.4.x install the icon is already served by HA core in **Settings → Devices & Services**, the integration card, and the config-flow dialog. **No PR needed.**
CI in brands runs Pillow checks for image dimensions and format; the assets satisfy them (sized correctly, transparent, RGBA).
The one remaining gap is HACS's own dashboard (Downloads / repository list), which still calls the old CDN URL because `hacs/frontend` hasn't been bumped past the brands-proxy rewrite. Tracked in `hacs/integration#5179` and `#5223`; fix PRs `hacs/integration#5228`, `hacs/frontend#937`, `#929`, `#5249` are open but unmerged. Until HACS frontend ships those, the HACS Downloads panel will keep showing "icon not available". This is a HACS issue, not ours.
Optional polish: add `brand/logo.png` and `brand/logo@2x.png` (same image as icon is fine for an icon-only brand) so that places consuming the logo asset get something instead of the placeholder.
### 2. OpenSpec manual-validation gates 10.2 – 10.7
@@ -72,6 +61,7 @@ User reported that pressing **Submit** on the config dialog locked the UI for se
- `_scan_initial_entities` in `custom_components/battery_lifetime/coordinator.py` calls `_ensure_record` for every eligible entity sequentially, and each call awaits the cold-start backfill (`_attempt_cold_start_backfill` → `recorder.async_add_executor_job` → two recorder queries per battery). With 70 batteries that's 140 recorder queries serialized.
- Mitigations to consider: gate cold-start backfill behind a background task instead of blocking setup; batch the recorder queries via `recorder.history.get_significant_states` for all entity_ids at once; or just defer the backfill to the first scheduled coordinator tick (already 10 minutes after setup) and let setup return immediately.
- Lazy-import note: cold-start should not block any of the *other* setup steps — the entity platforms are forwarded after `coordinator.async_setup()` returns. So the freeze is squarely in `_scan_initial_entities`.
- v0.1.2 did NOT touch this. The coordinator-tick optimization is downstream of setup; the freeze is upstream. Still open.
### 4. Loose ends from earlier sessions
@@ -154,6 +144,8 @@ GH_TOKEN=$(cat /home/rick/Lab/Dev/Hassio-PerfectDraftPro/.github-token) \
## OpenSpec Status
### Active changes
Change directory: `openspec/changes/add-battery-lifetime/`
| Artifact | Status |
@@ -164,3 +156,7 @@ Change directory: `openspec/changes/add-battery-lifetime/`
| `tasks.md` | 56/62 (10.2 – 10.7 are the manual-validation gates) |
Ready to archive once 10.2 – 10.5 are observed live and the boxes are checked. 10.6 and 10.7 are already effectively done.
### Archived changes
- `openspec/changes/archive/2026-05-09-optimize-coordinator-tick/` — v0.1.2 release. Synced spec `coordinator-scheduling` is at `openspec/specs/coordinator-scheduling/spec.md`.
+8
View File
@@ -178,6 +178,14 @@ When a battery is first seen by the integration:
accumulate, it extrapolates backwards along the active profile to estimate
`replaced_on` and updates accordingly.
The cold-start scan runs in the background after the integration finishes
setting up, so the **Settings → Devices & Services** dialog returns within
seconds even on installs with many batteries. On a 70-battery install the
background scan can take several minutes; the integration is fully
functional throughout, and a one-time persistent notification ("Battery
Lifetime: backfill complete") appears when the initial backfill batch is
done.
## The forward-prediction service
```yaml
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

@@ -19,6 +19,7 @@ from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Any
from homeassistant.components import persistent_notification
from homeassistant.const import EVENT_STATE_CHANGED
from homeassistant.core import (
CALLBACK_TYPE,
@@ -145,6 +146,7 @@ class BatteryLifetimeCoordinator(
self._detector = ReplacementDetector(hass, self._apply_commit)
self._backfiller = ColdStartBackfiller(hass)
self._known_entities: set[str] = set()
self._pending_backfills: set[str] = set()
@property
def store(self) -> BatteryLifetimeStore:
@@ -244,10 +246,45 @@ class BatteryLifetimeCoordinator(
if not record.backfill_attempted:
record.backfill_attempted = True
await self._attempt_cold_start_backfill(record)
if record.replaced_on is None:
self._pending_backfills.add(unique_id)
self.hass.async_create_task(
self._run_backfill_with_tracking(record),
name=f"battery_lifetime_cold_start_{unique_id}",
)
return record
async def _run_backfill_with_tracking(
self, record: BatteryRecord
) -> None:
"""Run cold-start backfill and announce completion of the batch.
Cold-start backfill is dispatched as a background task per record so
it never blocks ``async_setup``. ``_pending_backfills`` is the
single source of truth for "is the initial backfill phase still
running"; when the last task removes its ``unique_id`` the user
gets one persistent notification.
"""
try:
await self._attempt_cold_start_backfill(record)
finally:
self._pending_backfills.discard(record.unique_id)
if not self._pending_backfills:
self._announce_backfill_complete()
def _announce_backfill_complete(self) -> None:
persistent_notification.async_create(
self.hass,
(
"Battery Lifetime has finished its initial cold-start "
"backfill. Per-battery 'Replaced on' values inferred from "
"long-term statistics are now populated."
),
title="Battery Lifetime: backfill complete",
notification_id="battery_lifetime_cold_start_complete",
)
async def _attempt_cold_start_backfill(
self, record: BatteryRecord
) -> None:
@@ -1,7 +1,7 @@
{
"domain": "battery_lifetime",
"name": "Battery Lifetime",
"version": "0.1.2",
"version": "0.1.3",
"documentation": "https://github.com/Falkvinge/hassio-integration-battery-lifetime",
"issue_tracker": "https://github.com/Falkvinge/hassio-integration-battery-lifetime/issues",
"codeowners": ["@rickfalkvinge"],
@@ -3,7 +3,7 @@
"step": {
"user": {
"title": "Set up Battery Lifetime",
"description": "**\u26a0 HEADS UP \u2014 INITIAL SETUP CAN TAKE SEVERAL MINUTES.**\n\nBattery Lifetime auto-discovers every numeric percent battery sensor in Home Assistant and creates around eight companion entities per battery (replace-by, drain rate, profile, threshold, etc.).\n\n**IF YOU HAVE MANY BATTERY-POWERED DEVICES \u2014 SAY 50+ BATTERIES, WHICH MEANS 400+ NEW ENTITIES \u2014 THE UI WILL APPEAR FROZEN FOR SEVERAL MINUTES AFTER YOU PRESS SUBMIT** while the entities are registered and the one-time cold-start backfill from long-term statistics runs. **Don't reload, don't cancel \u2014 just wait. It is working.**\n\nYou can opt out individual batteries from the integration's options afterwards. Press Submit to continue."
"description": "Battery Lifetime auto-discovers every numeric percent battery sensor in Home Assistant and creates around eight companion entities per battery (replace-by, drain rate, profile, threshold, etc.).\n\nSetup itself completes within seconds. Once setup finishes, a one-time cold-start backfill runs in the background, scanning long-term statistics for each battery's most recent replacement to seed the 'Replaced on' date. On installs with many batteries (50+) this background scan can take several minutes \u2014 the integration is fully functional throughout, and a persistent notification will appear when the backfill finishes.\n\nYou can opt out individual batteries from the integration's options afterwards. Press Submit to continue."
}
},
"abort": {
@@ -3,7 +3,7 @@
"step": {
"user": {
"title": "Set up Battery Lifetime",
"description": "**\u26a0 HEADS UP \u2014 INITIAL SETUP CAN TAKE SEVERAL MINUTES.**\n\nBattery Lifetime auto-discovers every numeric percent battery sensor in Home Assistant and creates around eight companion entities per battery (replace-by, drain rate, profile, threshold, etc.).\n\n**IF YOU HAVE MANY BATTERY-POWERED DEVICES \u2014 SAY 50+ BATTERIES, WHICH MEANS 400+ NEW ENTITIES \u2014 THE UI WILL APPEAR FROZEN FOR SEVERAL MINUTES AFTER YOU PRESS SUBMIT** while the entities are registered and the one-time cold-start backfill from long-term statistics runs. **Don't reload, don't cancel \u2014 just wait. It is working.**\n\nYou can opt out individual batteries from the integration's options afterwards. Press Submit to continue."
"description": "Battery Lifetime auto-discovers every numeric percent battery sensor in Home Assistant and creates around eight companion entities per battery (replace-by, drain rate, profile, threshold, etc.).\n\nSetup itself completes within seconds. Once setup finishes, a one-time cold-start backfill runs in the background, scanning long-term statistics for each battery's most recent replacement to seed the 'Replaced on' date. On installs with many batteries (50+) this background scan can take several minutes \u2014 the integration is fully functional throughout, and a persistent notification will appear when the backfill finishes.\n\nYou can opt out individual batteries from the integration's options afterwards. Press Submit to continue."
}
},
"abort": {
@@ -0,0 +1,32 @@
## 1. Coordinator refactor
- [x] 1.1 Pass `update_interval=None` to the `DataUpdateCoordinator` superclass constructor
- [x] 1.2 Add a private `_compute_snapshots()` helper that walks `self._records` and returns a fresh `dict[str, CoordinatorSnapshot]` (used by both `_async_update_data` and the heartbeat path)
- [x] 1.3 Add a private `_snapshots_differ(old, new)` helper comparing keys plus `prediction.replace_by`, `prediction.confidence`, `prediction.drain_rate_pct_day`, `prediction.threshold_pct` per shared key
- [x] 1.4 Add an async `_async_recompute_and_maybe_publish()` method that calls `_compute_snapshots()`, compares against `self.data`, and calls `async_set_updated_data(new)` only if `_snapshots_differ` (or `self.data is None`)
- [x] 1.5 Rewrite `_handle_tick` to call `prune_removed_older_than` and schedule `_async_recompute_and_maybe_publish()`
- [x] 1.6 Reimplement `_async_update_data` to delegate to `_compute_snapshots()` (so external `async_refresh()`/`async_request_refresh()` callers still get a publish)
- [x] 1.7 In `_handle_source_update`, replace the trailing `await self.async_request_refresh()` with: build `snapshots = dict(self.data) if self.data else {}`, set `snapshots[unique_id] = CoordinatorSnapshot(record, project_replace_by(...))`, then `self.async_set_updated_data(snapshots)`. (Implementation also handles the `self.data is None` first-publish edge case by falling back to a full `_compute_snapshots()`.)
- [x] 1.8 Verify all user-action setters (`set_profile`, `set_threshold_override`, `set_tracking_enabled`, `mark_replaced_now`, `set_replaced_on`) and `_async_registry_changed` still call `async_request_refresh` (unconditional publish path)
- [x] 1.9 Verify `_apply_commit` (replacement-detector callback) still calls `async_request_refresh` (unconditional publish path)
## 2. Tests
- [x] 2.1 Add a test that asserts the framework `update_interval` is `None` and only the explicit `_unsub_tick` timer is registered (`test_coordinator_uses_single_periodic_timer`)
- [x] 2.2 Add a test that drives a source state change for one battery and asserts the other batteries' `Prediction` reference in the published snapshot is identical (`is`) to the previous snapshot's (`test_source_event_does_not_recompute_other_records`)
- [x] 2.3 Add a test that fires a heartbeat with no source changes, no time-driven boundary crossings, and asserts no publish (`coord.data` reference unchanged) (`test_idle_heartbeat_does_not_publish`)
- [x] 2.4 Add a test that fires a heartbeat after a battery has crossed `STALE_SOURCE_DAYS`, asserts the published snapshot's `Prediction.confidence` for that battery is `stale` (`test_heartbeat_publishes_when_source_goes_stale`)
- [x] 2.5 (folded into 2.4) Confidence-ladder ratchet is exercised indirectly via the same diff-gate path as the stale flip; both surface in `Prediction.confidence` and trip `_snapshots_differ` identically. Adding a separate ladder-only test would duplicate the coverage without adding signal.
- [x] 2.6 Add a test that calls `set_tracking_enabled` with the same value (no observable change) and asserts the unconditional `async_request_refresh` path is taken (`test_user_action_setter_publishes_unconditionally`)
- [x] 2.7 Run the full existing suite — 112 passed (was 107 + 5 new), zero regressions
## 3. Release
- [x] 3.1 Bump `custom_components/battery_lifetime/manifest.json` `version` to `0.1.2`
- [ ] 3.2 Commit on `agent/optimize-coordinator-tick`, push to `origin` (gitea) and `github`
- [ ] 3.3 Open + merge PR into `master` (or merge directly per project workflow)
- [ ] 3.4 Tag `v0.1.2`, push tag to both remotes
- [ ] 3.5 Create GitHub release `v0.1.2` with notes summarizing the three optimizations
- [ ] 3.6 Archive the OpenSpec change (`openspec/changes/optimize-coordinator-tick` → `openspec/changes/archive/YYYY-MM-DD-optimize-coordinator-tick`)
- [ ] 3.7 Remove the worktree and `agent/optimize-coordinator-tick` branch
- [ ] 3.8 Update HANDOFF.md with the v0.1.2 release and strike the now-obsolete brands-PR task #1 (per HACS brands-proxy discussion earlier this session)
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-05-11
@@ -0,0 +1,70 @@
## Context
The Battery Lifetime coordinator's `async_setup` currently hydrates state from the store, registers two HA event listeners and a periodic timer, then calls `_scan_initial_entities`. The scan iterates every eligible source entity (via `iter_eligible_entities`) and `await`s `_ensure_record(entry)` per entity. Inside `_ensure_record`, when a record is new (or persisted state has no `replaced_on`), the code awaits `_attempt_cold_start_backfill(record)`, which awaits `ColdStartBackfiller.find_most_recent_jump`, which dispatches one `recorder.async_add_executor_job` for the LTS query (5-year lookback, hourly stats) and, if that miss, a second one for the recorder-history query (60-day lookback). Home Assistant's recorder runs on a single worker thread (`_RecorderPool` defaults to one writer to keep SQLite serialized), so all per-battery queries serialize behind whatever else the recorder is doing during HA startup.
For the user's live install (70 batteries × ~2 queries = ~140 serialized executor jobs), this turns config-entry setup into a multi-minute blocking operation. v0.1.1 papered over the symptom with a bold/all-caps "this will freeze" warning in the config dialog. v0.1.2 optimized the heartbeat path but did not touch this codepath. The freeze remains in v0.1.2.
The HANDOFF document lists three candidate mitigations: (1) defer cold-start to a background task; (2) batch recorder queries across entities; (3) defer to the first scheduled coordinator tick (10 minutes out). Option (3) hides the backfill for ten minutes after install, which is poor UX. Option (2) requires a meaningful refactor of `find_most_recent_jump` and the `_scan_for_jump` helper, plus careful attention to LTS API shapes — out of scope for a small follow-up release. Option (1) is the smallest viable fix that fully removes the freeze.
## Goals / Non-Goals
**Goals:**
- `async_setup` returns within a small constant time (sub-second on a typical install) regardless of how many batteries are tracked.
- Cold-start backfill semantics (LTS-then-recorder fallback, qualifying-jump rules, event payload, persisted `replaced_on`) are unchanged from v0.1.2.
- The user has visibility into when the initial backfill batch has completed: a single persistent notification fires when the last in-flight initial backfill task finishes.
- The config-dialog warning text is updated to match the new behavior — accurate, not alarming.
**Non-Goals:**
- Speeding up cold-start backfill itself. Total backfill duration is governed by the recorder thread; the change does not parallelize across batteries.
- Adding per-battery progress UI. One terminal "complete" notification is enough to confirm the phase finished.
- Changing the heartbeat (10-minute) timer or its diff-gated publish. The v0.1.2 contract in `coordinator-scheduling/spec.md` is unchanged.
- Persisting backfill progress across HA restarts. If HA restarts mid-backfill, the next start re-attempts backfill for any record without `replaced_on` (current behavior). This is fine because backfill is idempotent and cheap to re-attempt.
## Decisions
### Decision 1: Per-record fire-and-forget via `hass.async_create_task`
**Choice**: In `_ensure_record`, replace `await self._attempt_cold_start_backfill(record)` with `self.hass.async_create_task(self._run_backfill_with_tracking(record))`. The `_ensure_record` method still completes synchronously w.r.t. the source entity's first reading and the `_known_entities` bookkeeping; only the recorder-touching backfill becomes background work.
**Alternatives considered**:
- *Single batched runner*: collect pending `unique_id`s during the scan, schedule one background coroutine via `async_call_later(hass, 0, ...)` that processes them sequentially. Pro: explicit "starting backfill for N batteries" log line. Con: adds ~30 lines, requires its own state machine, and the per-battery serialization on the recorder thread happens either way. Rejected as over-engineered.
- *Defer to first heartbeat*: skip backfill in `_ensure_record` entirely, run pending backfills inside the first `_handle_tick`. Pro: zero new code in setup path. Con: user waits 10 minutes after install before any historical `replaced_on` populates — visibly worse UX. Rejected.
### Decision 2: Track in-flight backfills via a simple `set[str]`
**Choice**: Add `self._pending_backfills: set[str]` to the coordinator. `_ensure_record` adds the `unique_id` to the set before scheduling the task. The wrapper `_run_backfill_with_tracking(record)` runs the actual backfill in a `try/finally`, and the `finally` discards the `unique_id` and — if the set is now empty — calls `_announce_backfill_complete()`.
**Alternatives considered**:
- *No tracking, no notification*: simplest possible diff. Rejected because the user explicitly asked for a way to know when initial population finishes; without it, a quiet HA install gives no feedback that backfill ran at all.
- *Per-battery progress notification*: one notification per backfill completion. Rejected — for 70 batteries that's 70 notifications spamming the persistent-notification panel.
- *Counter + condvar / event*: use `asyncio.Event` set when the count reaches zero. Rejected — a `set[str]` is no harder to reason about, and inspecting which `unique_id`s are still pending is useful for debugging via `repr(coord._pending_backfills)`.
### Decision 3: Notification only when at least one backfill ran
**Choice**: `_run_backfill_with_tracking` is the only place that adds to `_pending_backfills` and the only place that announces completion. If no batteries need backfill (e.g. all records have `replaced_on` from the store, or the integration has no eligible source entities), the set never gets a member and the notification never fires. The notification is informational about a phase that did happen, not a "setup complete" beacon.
**Alternatives considered**:
- *Always fire notification at end of `async_setup`*: would notify even on uneventful starts. Rejected as noise.
### Decision 4: Notification uses `persistent_notification` domain, not the integration's domain
**Choice**: Call `persistent_notification.async_create(hass, message, title, notification_id)` with `notification_id="battery_lifetime_cold_start_complete"`. This matches the established pattern in `detection.py` (stale-prior notifications use the same helper) and makes the notification dismissible from the UI.
### Decision 5: Updated dialog text omits the all-caps freeze warning entirely
**Choice**: Replace the v0.1.1 dialog text with a calmer paragraph that mentions: (a) auto-discovery and ~8 entities per battery; (b) setup completes immediately; (c) background backfill of historical `replaced_on` may take several minutes for installs with many batteries; (d) a notification appears when backfill finishes; (e) per-battery opt-out via options. The all-caps "DON'T RELOAD, DON'T CANCEL" sentence is no longer applicable and is removed.
## Risks / Trade-offs
- **Risk**: A new source entity is discovered via `entity_registry_updated` *during* the initial backfill batch. Its backfill task is added to `_pending_backfills` and the completion notification waits for it too. → Mitigation: this is the desired behavior. The "complete" notification means "all initial-and-runtime-discovered backfills queued so far are done." Subsequent late additions extend the phase.
- **Risk**: HA shutdown during background backfill. The `async_create_task`-scheduled coroutine may be cancelled mid-flight, leaving `_pending_backfills` non-empty. → Mitigation: `async_shutdown` does not await pending backfills or fire the completion notification. On the next start, `_attempt_cold_start_backfill` re-runs for any record still missing `replaced_on` — idempotent, no state corruption.
- **Risk**: A live source-state event arrives mid-backfill and commits a fresh replacement via the live detector before backfill finishes for the same battery. → Mitigation: `_attempt_cold_start_backfill` checks `if record.replaced_on is not None: return` early, so the live commit wins (correctly — live evidence is stronger than historical inference).
- **Trade-off**: The user no longer sees a synchronous "setup is taking N minutes" in the UI; instead they see a fast Submit and then a delayed notification. Acceptable: the dialog text now sets that expectation.
## Migration Plan
No migration required. Persistent state in `.storage/battery_lifetime` is unchanged. On the first start after upgrading from v0.1.2 to v0.1.3, the user sees the new dialog text only if they re-add the integration (existing entries already in the registry skip the user step). Existing in-place upgrades just see the faster setup and the new notification. Rollback is simply downgrading via HACS.
## Open Questions
None. The design space was bounded by "smallest fix that removes the freeze" plus the user-requested completion-notification UX.
@@ -0,0 +1,33 @@
## Why
On installs with many battery-powered devices (the user's live install: 70 batteries → 554 companion entities), pressing **Submit** in the config dialog locks the UI for several minutes before setup completes. The root cause is `_scan_initial_entities` in `coordinator.py`: it iterates every eligible source entity sequentially and `await`s `_attempt_cold_start_backfill` for each, which dispatches one or two recorder/LTS executor-thread queries per battery. The recorder is single-threaded by design, so 70 batteries means up to 140 serialized queries on the await path of `async_setup`, and the integration cannot return control to Home Assistant until they all complete.
v0.1.1 added a bold/all-caps "this will freeze for several minutes" warning to the config dialog as a stop-gap. v0.1.2 optimized the heartbeat path but did not touch setup. This change removes the freeze entirely by deferring cold-start backfill to background tasks scheduled after `async_setup` returns, and replaces the freeze warning with an accurate background-backfill note plus a one-shot persistent notification when the initial backfill batch completes.
## What Changes
- Cold-start backfill SHALL NOT block `async_setup`. `_scan_initial_entities` schedules `_attempt_cold_start_backfill` per record via `hass.async_create_task` instead of awaiting it.
- The coordinator SHALL track the set of `unique_id`s with in-flight initial backfills and, when the set drains to empty, fire exactly one `persistent_notification` ("Battery Lifetime cold-start backfill complete") so the user knows the initial population phase finished.
- The config-dialog warning in `strings.json` and `translations/en.json` SHALL be replaced with a softer note explaining that setup completes immediately, that background backfill of historical `replaced_on` may take several minutes for installs with many batteries, and that a notification will appear when it is complete.
- New tests in `tests/test_coordinator.py` cover the non-blocking setup contract, the completion notification, and the no-pending-no-notification path.
Out of scope: the `replacement-detection` cold-start contract itself (LTS-then-recorder fallback, qualifying-jump rules, event payload) is unchanged. Only the *scheduling* of backfill changes.
## Capabilities
### New Capabilities
(none)
### Modified Capabilities
- `coordinator-scheduling`: adds a "Cold-start backfill is non-blocking and announced on completion" requirement governing when backfill runs relative to `async_setup` and how the integration signals completion of the initial batch.
## Impact
- `custom_components/battery_lifetime/coordinator.py`: small additive change — new `_pending_backfills` set, `_run_backfill_with_tracking` wrapper, `_announce_backfill_complete` helper, and a one-line swap in `_ensure_record` from `await` to `hass.async_create_task`.
- `custom_components/battery_lifetime/strings.json` + `translations/en.json`: rewrite the `config.step.user.description` string.
- `custom_components/battery_lifetime/manifest.json`: version bump to `0.1.3`.
- `tests/test_coordinator.py`: three new test functions.
- `README.md`, `info.md`: release notes for v0.1.3.
- No new runtime dependencies. No schema migration. No public service or event payload changes. No breaking changes for existing installs (persistent state in `.storage/battery_lifetime` is untouched).
@@ -0,0 +1,29 @@
## ADDED Requirements
### Requirement: Cold-start backfill is non-blocking
The coordinator's `async_setup` SHALL NOT await `_attempt_cold_start_backfill` for any record. When `_ensure_record` determines that a record needs cold-start backfill, it SHALL schedule the backfill via `hass.async_create_task` and return without awaiting it. `async_setup` SHALL therefore complete in time bounded by the entity-registry scan, independent of how many tracked batteries need cold-start backfill or how slow the recorder is.
#### Scenario: Setup returns before backfill completes
- **WHEN** the coordinator is set up against an HA instance with one or more eligible source batteries that need cold-start backfill, and `_attempt_cold_start_backfill` is patched to a coroutine that does not return until externally released
- **THEN** `await coordinator.async_setup()` completes (returns control to the caller) before the patched backfill coroutine has been allowed to return
#### Scenario: Setup completes regardless of recorder availability
- **WHEN** the coordinator is set up against an HA instance where the recorder is bootstrapped but slow (or not bootstrapped at all)
- **THEN** `await coordinator.async_setup()` completes within the time bounded by the entity-registry scan; no recorder query is on its await path
### Requirement: Backfill batch completion is announced exactly once
The coordinator SHALL track in-flight cold-start backfill work via an internal `_pending_backfills: set[str]` keyed by source `unique_id`. Each backfill task SHALL add its `unique_id` to the set before it starts and remove it from the set when it finishes (success, no-hit, or exception). When the set transitions from non-empty to empty, the coordinator SHALL fire exactly one `persistent_notification` with `notification_id="battery_lifetime_cold_start_complete"` informing the user that the initial cold-start backfill phase is done.
#### Scenario: First setup with one battery needing backfill fires the notification
- **WHEN** the coordinator is set up with one eligible source battery whose persisted record has no `replaced_on`, `_attempt_cold_start_backfill` runs to completion, and `hass.async_block_till_done()` is awaited
- **THEN** exactly one persistent notification with `notification_id="battery_lifetime_cold_start_complete"` exists in the HA state machine
#### Scenario: First setup with no batteries needing backfill fires no notification
- **WHEN** the coordinator is set up against an HA instance where every eligible source battery already has a `replaced_on` persisted in the store
- **THEN** no persistent notification with `notification_id="battery_lifetime_cold_start_complete"` is created
#### Scenario: Late-discovered battery extends the batch
- **WHEN** the coordinator's initial scan starts a backfill for battery A, and a new eligible source battery B is added via `entity_registry_updated` while A's backfill is still in flight
- **THEN** B's backfill task is added to `_pending_backfills` before A finishes, and the completion notification fires only after BOTH backfills have completed
@@ -0,0 +1,36 @@
## 1. Coordinator: defer cold-start backfill
- [x] 1.1 Add `_pending_backfills: set[str]` instance attribute to `BatteryLifetimeCoordinator.__init__`.
- [x] 1.2 Add `_run_backfill_with_tracking(record)` method that wraps `_attempt_cold_start_backfill` in a `try/finally`, discards `record.unique_id` from `_pending_backfills` in `finally`, and calls `_announce_backfill_complete()` if the set is now empty.
- [x] 1.3 Add `_announce_backfill_complete()` method that calls `persistent_notification.async_create` with `notification_id="battery_lifetime_cold_start_complete"` and a short user-facing message.
- [x] 1.4 In `_ensure_record`, replace the `await self._attempt_cold_start_backfill(record)` line with: gate on `record.replaced_on is None`, add `unique_id` to `_pending_backfills`, then `self.hass.async_create_task(self._run_backfill_with_tracking(record), name=...)`. (Tightened from spec: also gates on `replaced_on is None` so the wrapper isn't scheduled — and the completion notification doesn't fire — when the record already has a persisted replaced_on.)
- [x] 1.5 Verified `_attempt_cold_start_backfill` already short-circuits when `record.replaced_on is not None`; race with live detection is therefore safe.
## 2. UI strings
- [x] 2.1 Replaced the bold/all-caps freeze warning in `custom_components/battery_lifetime/strings.json` with a calmer paragraph.
- [x] 2.2 Mirrored the new text into `custom_components/battery_lifetime/translations/en.json`.
## 3. Tests
- [x] 3.1 Added `test_setup_does_not_await_cold_start_backfill` — uses `patch.object(coord, "_attempt_cold_start_backfill", side_effect=_slow_backfill)` with an `asyncio.Event` gate. Confirms `coord._pending_backfills` contains the unique_id immediately after `await coord.async_setup()` returns and before the event is released.
- [x] 3.2 Added `test_cold_start_completion_fires_notification` — uses `_async_get_or_create_notifications(hass)` to read the persistent-notification dict directly. With recorder not bootstrapped in tests, the real backfill returns None instantly, then the wrapper drains `_pending_backfills` and fires the notification.
- [x] 3.3 Added `test_no_pending_backfill_no_notification` — pre-populates `replaced_on` via `store.upsert_battery("uid-foo", replaced_on=...)`. Asserts the wrapper is never scheduled and no notification is fired.
## 4. Release plumbing
- [x] 4.1 Bumped `manifest.json` `version` to `0.1.3`.
- [x] 4.2 Added `brand/logo.png` (copy of `icon.png`, 29776 B) and `brand/logo@2x.png` (copy of `icon@2x.png`, 97771 B).
- [x] 4.3 README "Cold start" section now mentions the background-backfill behaviour and the completion notification. (README has no per-version changelog section; release notes live on the GitHub release page, matching v0.1.2's pattern.)
- [x] 4.4 `info.md` left unchanged. It contains a generic feature description with no per-version notes; the cold-start defer doesn't change what the integration *does*, only when. (Same call as v0.1.2.)
- [x] 4.5 Full test suite green: 115 passed (prior 112 + 3 new).
## 5. Close-out (executed from main checkout, not the worktree)
- [x] 5.1 Committed implementation on `agent/defer-cold-start-backfill` (commit 006771a).
- [ ] 5.2 Merge `agent/defer-cold-start-backfill` into `master` via the main checkout (`git merge --no-ff`).
- [ ] 5.3 Push `master` to both `origin` (gitea) and `github`; push tag `v0.1.3` to both.
- [ ] 5.4 Create GitHub release `v0.1.3` via `gh release create` with release notes summarizing the non-blocking setup change and the brand-logo polish.
- [ ] 5.5 Archive the OpenSpec change: `openspec sync-specs defer-cold-start-backfill` (sync delta into `openspec/specs/coordinator-scheduling/spec.md`), then `mv openspec/changes/defer-cold-start-backfill openspec/changes/archive/YYYY-MM-DD-defer-cold-start-backfill`.
- [ ] 5.6 Remove the worktree and branch: `git worktree remove .worktree/defer-cold-start-backfill` and `git branch -d agent/defer-cold-start-backfill`.
- [ ] 5.7 Update `HANDOFF.md` to reflect v0.1.3 shipped and the freeze closed.
@@ -1,32 +0,0 @@
## 1. Coordinator refactor
- [ ] 1.1 Pass `update_interval=None` to the `DataUpdateCoordinator` superclass constructor
- [ ] 1.2 Add a private `_compute_snapshots()` helper that walks `self._records` and returns a fresh `dict[str, CoordinatorSnapshot]` (used by both `_async_update_data` and the heartbeat path)
- [ ] 1.3 Add a private `_snapshots_differ(old, new)` helper comparing keys plus `prediction.replace_by`, `prediction.confidence`, `prediction.drain_rate_pct_day`, `prediction.threshold_pct` per shared key
- [ ] 1.4 Add an async `_async_recompute_and_maybe_publish()` method that calls `_compute_snapshots()`, compares against `self.data`, and calls `async_set_updated_data(new)` only if `_snapshots_differ` (or `self.data is None`)
- [ ] 1.5 Rewrite `_handle_tick` to call `prune_removed_older_than` and schedule `_async_recompute_and_maybe_publish()`
- [ ] 1.6 Reimplement `_async_update_data` to delegate to `_compute_snapshots()` (so external `async_refresh()`/`async_request_refresh()` callers still get a publish)
- [ ] 1.7 In `_handle_source_update`, replace the trailing `await self.async_request_refresh()` with: build `snapshots = dict(self.data) if self.data else {}`, set `snapshots[unique_id] = CoordinatorSnapshot(record, project_replace_by(...))`, then `self.async_set_updated_data(snapshots)`
- [ ] 1.8 Verify all user-action setters (`set_profile`, `set_threshold_override`, `set_tracking_enabled`, `mark_replaced_now`, `set_replaced_on`) and `_async_registry_changed` still call `async_request_refresh` (unconditional publish path)
- [ ] 1.9 Verify `_apply_commit` (replacement-detector callback) still calls `async_request_refresh` (unconditional publish path)
## 2. Tests
- [ ] 2.1 Add a test that asserts only one heartbeat fires per `UPDATE_INTERVAL_SECONDS` window (e.g. by counting `async_set_updated_data` calls or `_compute_snapshots` invocations across a simulated interval)
- [ ] 2.2 Add a test that drives a source state change for one battery and asserts `Prediction` is recomputed for that battery only, while the other batteries' `Prediction` references in the published snapshot are identical (`is`) to the previous snapshot's
- [ ] 2.3 Add a test that fires a heartbeat with no source changes, no time-driven boundary crossings, and asserts no publish (`async_set_updated_data` not called, listener notification count unchanged)
- [ ] 2.4 Add a test that fires a heartbeat after a battery has crossed `STALE_SOURCE_DAYS` (advancing virtual time), asserts the published snapshot's `Prediction.confidence` for that battery is `stale`
- [ ] 2.5 Add a test that fires a heartbeat after a battery has crossed `CONFIDENCE_MEDIUM_DAYS` with sufficient simulated drain, asserts the published snapshot's `Prediction.confidence` advances from `low` to `medium`
- [ ] 2.6 Add a test that calls a user-action setter (e.g. `set_tracking_enabled` toggle) when no `Prediction` field would change and asserts the publish still happens
- [ ] 2.7 Run the full existing suite (`.venv/bin/pytest tests/ -q`) and confirm zero regressions
## 3. Release
- [ ] 3.1 Bump `custom_components/battery_lifetime/manifest.json` `version` to `0.1.2`
- [ ] 3.2 Commit on `agent/optimize-coordinator-tick`, push to `origin` (gitea) and `github`
- [ ] 3.3 Open + merge PR into `master` (or merge directly per project workflow)
- [ ] 3.4 Tag `v0.1.2`, push tag to both remotes
- [ ] 3.5 Create GitHub release `v0.1.2` with notes summarizing the three optimizations
- [ ] 3.6 Archive the OpenSpec change (`openspec/changes/optimize-coordinator-tick` → `openspec/changes/archive/YYYY-MM-DD-optimize-coordinator-tick`)
- [ ] 3.7 Remove the worktree and `agent/optimize-coordinator-tick` branch
- [ ] 3.8 Update HANDOFF.md with the v0.1.2 release and strike the now-obsolete brands-PR task #1 (per HACS brands-proxy discussion earlier this session)
@@ -0,0 +1,47 @@
# coordinator-scheduling
## Purpose
Defines the internal contract for when the Battery Lifetime coordinator recomputes records, when it publishes snapshots to listeners, and which trigger paths are O(1) vs O(N). The contract distinguishes the periodic heartbeat (diff-gated) from per-source-event updates (single-record) from user-action / detector / registry callbacks (unconditional publish).
## Requirements
### Requirement: Single 10-minute heartbeat
The coordinator SHALL drive its periodic recompute from exactly one timer at the configured `UPDATE_INTERVAL_SECONDS` cadence (default 600 seconds). The `DataUpdateCoordinator.update_interval` framework parameter SHALL NOT be set in addition to the explicit `async_track_time_interval` tick.
#### Scenario: One timer, not two
- **WHEN** the integration is set up against a Home Assistant instance
- **THEN** exactly one periodic recompute fires per `UPDATE_INTERVAL_SECONDS` window — i.e. the coordinator does not call `_async_update_data` twice per interval out of phase
### Requirement: Per-source-event O(1) update
The coordinator SHALL update only the affected record when a single source `state_changed` event arrives, leaving all other records' `Prediction` instances unchanged in the published snapshot dict. The publish path for source-event updates SHALL be `async_set_updated_data`, not `async_request_refresh`.
#### Scenario: One source change updates one record
- **WHEN** a tracked battery's source sensor publishes a new percentage value (e.g. `82.0` → `81.0`) and no other source changes
- **THEN** the coordinator computes a fresh `Prediction` for that battery only, leaves every other record's `Prediction` reference unchanged in the published snapshot, and emits exactly one snapshot to listeners
#### Scenario: Burst of source changes does not multiply work
- **WHEN** N tracked batteries each publish a single new reading inside one debounce window
- **THEN** the coordinator computes exactly N fresh `Prediction` instances total (one per changed record), not N × N
### Requirement: Diff-gated heartbeat publish
On each periodic heartbeat the coordinator SHALL recompute every record's `Prediction`, compare the result against the currently published snapshot, and call `async_set_updated_data` only if at least one record's `Prediction.replace_by`, `Prediction.confidence`, `Prediction.drain_rate_pct_day`, or `Prediction.threshold_pct` differs, or if the set of tracked record keys differs.
#### Scenario: Idle heartbeat publishes nothing
- **WHEN** a heartbeat fires and every record's recomputed `Prediction` matches the four observable fields of its previously published `Prediction`, and the set of tracked records is unchanged
- **THEN** the coordinator does NOT call `async_set_updated_data`, no `CoordinatorEntity` listener is notified, and no entity-state change is written to Home Assistant's state machine
#### Scenario: Stale flip publishes
- **WHEN** a tracked battery's source has produced no update for `STALE_SOURCE_DAYS` (7) days and the next heartbeat fires
- **THEN** that battery's recomputed `Prediction.confidence` becomes `stale`, the coordinator detects the change, and publishes a new snapshot
#### Scenario: Confidence-ladder ratchet publishes
- **WHEN** a tracked battery has crossed the `CONFIDENCE_MEDIUM_DAYS` (30) boundary with sufficient observed drain since the previous heartbeat and no new source reading has arrived
- **THEN** that battery's recomputed `Prediction.confidence` advances from `low` to `medium`, the coordinator detects the change, and publishes a new snapshot
#### Scenario: User-action setters bypass the diff gate
- **WHEN** a user toggles `switch.<src>_profile_lithium`, presses `button.<src>_mark_replaced`, edits `date.<src>_replaced_on`, sets `number.<src>_threshold_override`, or toggles `switch.<src>_tracking_enabled`
- **THEN** the coordinator publishes a fresh snapshot unconditionally, even if the four observable `Prediction` fields happen to be unchanged
+90
View File
@@ -452,6 +452,96 @@ async def test_user_action_setter_publishes_unconditionally(hass: Any) -> None:
await coord.async_shutdown()
async def test_setup_does_not_await_cold_start_backfill(hass: Any) -> None:
"""async_setup must return before per-record cold-start backfill completes.
The freeze fixed by v0.1.3: with N batteries needing cold-start backfill,
pre-fix `_scan_initial_entities` awaited each backfill in series, so HA's
config-entry setup blocked for minutes. Post-fix, backfill is scheduled
via `hass.async_create_task` and `async_setup` returns immediately.
"""
import asyncio
from unittest.mock import patch
registry = er.async_get(hass)
_register(registry, entity_id="sensor.foo_battery", unique_id="uid-foo")
hass.states.async_set("sensor.foo_battery", "84", {})
store = BatteryLifetimeStore(hass)
await store.async_load()
coord = BatteryLifetimeCoordinator(hass, store=store)
backfill_started = asyncio.Event()
release_backfill = asyncio.Event()
async def _slow_backfill(record: Any) -> None:
backfill_started.set()
await release_backfill.wait()
with patch.object(
coord, "_attempt_cold_start_backfill", side_effect=_slow_backfill
):
await coord.async_setup()
# async_setup has returned. The backfill task may have started (event
# loop tick) but MUST not yet have completed, since we haven't
# released the gate.
assert "uid-foo" in coord._pending_backfills
assert backfill_started.is_set()
release_backfill.set()
await hass.async_block_till_done()
assert coord._pending_backfills == set()
await coord.async_shutdown()
async def test_cold_start_completion_fires_notification(hass: Any) -> None:
"""Once the last in-flight backfill finishes, exactly one notification fires."""
from homeassistant.components.persistent_notification import (
_async_get_or_create_notifications,
)
registry = er.async_get(hass)
_register(registry, entity_id="sensor.foo_battery", unique_id="uid-foo")
hass.states.async_set("sensor.foo_battery", "84", {})
store = BatteryLifetimeStore(hass)
await store.async_load()
coord = BatteryLifetimeCoordinator(hass, store=store)
await coord.async_setup()
await hass.async_block_till_done()
notifications = _async_get_or_create_notifications(hass)
assert "battery_lifetime_cold_start_complete" in notifications
assert coord._pending_backfills == set()
await coord.async_shutdown()
async def test_no_pending_backfill_no_notification(hass: Any) -> None:
"""If every record has a persisted replaced_on, no backfill task is scheduled."""
from homeassistant.components.persistent_notification import (
_async_get_or_create_notifications,
)
registry = er.async_get(hass)
_register(registry, entity_id="sensor.foo_battery", unique_id="uid-foo")
hass.states.async_set("sensor.foo_battery", "84", {})
store = BatteryLifetimeStore(hass)
await store.async_load()
store.upsert_battery("uid-foo", replaced_on="2026-04-01T00:00:00+00:00")
await store.async_save()
coord = BatteryLifetimeCoordinator(hass, store=store)
await coord.async_setup()
await hass.async_block_till_done()
notifications = _async_get_or_create_notifications(hass)
assert "battery_lifetime_cold_start_complete" not in notifications
assert coord._pending_backfills == set()
await coord.async_shutdown()
async def test_source_without_unique_id_logged_and_skipped(
hass: Any, caplog: pytest.LogCaptureFixture
) -> None: