Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
089082a163 | ||
|
|
34ae5e8d01 | ||
|
|
13b3dd63ce | ||
|
|
8fab5a5784 | ||
|
|
c576310fce |
+14
-15
@@ -1,12 +1,12 @@
|
||||
# Agent Handoff — Battery Lifetime
|
||||
|
||||
## Current State (2026-05-09)
|
||||
## Current State (2026-05-11)
|
||||
|
||||
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 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.3** 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`.
|
||||
The OpenSpec changes `optimize-coordinator-tick` (v0.1.2) and `defer-cold-start-backfill` (v0.1.3) are fully archived under `openspec/changes/archive/2026-05-09-optimize-coordinator-tick/` and `openspec/changes/archive/2026-05-11-defer-cold-start-backfill/`. Both have their specs synced into `openspec/specs/coordinator-scheduling/spec.md`.
|
||||
|
||||
## What's Done
|
||||
|
||||
@@ -26,21 +26,20 @@ The OpenSpec change `optimize-coordinator-tick` (v0.1.2 release) is fully archiv
|
||||
- 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).
|
||||
- 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.
|
||||
- v0.1.3 defers cold-start backfill out of `async_setup`'s await chain via `hass.async_create_task`, removing the multi-minute config-entry freeze on installs with many batteries (the v0.1.1 dialog warning is no longer applicable and was softened). Adds a one-shot `persistent_notification` (`battery_lifetime_cold_start_complete`) when the initial backfill batch finishes. Ships `brand/logo.png` + `brand/logo@2x.png` (copies of the icon assets) for HA's Brands Proxy logo slot. 3 new tests in `tests/test_coordinator.py`, full suite 115 passed.
|
||||
- Both `master` and tags `v0.1.0`/`v0.1.1`/`v0.1.2`/`v0.1.3` 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 AND the non-blocking cold-start contract.
|
||||
|
||||
## What Needs Doing Next (Immediate)
|
||||
|
||||
### 1. ~~Brands PR for the HACS icon~~ — OBSOLETE as of HA 2026.3
|
||||
|
||||
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`).
|
||||
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`, `brand/logo.png`, and `brand/logo@2x.png` inside their own repository, and HA serves them from `/api/brands/integration/<domain>/...`. The `home-assistant/brands` repo **auto-closes** PRs for `custom_integrations/*` and tells contributors to use the inline mechanism.
|
||||
|
||||
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.**
|
||||
We ship all four assets as of v0.1.3 (icons in v0.1.1, logos added in v0.1.3 as copies of the icons). On the user's HA 2026.4.x install the icon and logo are served by HA core in **Settings → Devices & Services**, the integration card, and the config-flow dialog. **No PR needed.**
|
||||
|
||||
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
|
||||
|
||||
These are the only remaining tasks in `openspec/changes/add-battery-lifetime/tasks.md`. Some are implicitly being validated by the live install right now:
|
||||
@@ -54,14 +53,13 @@ These are the only remaining tasks in `openspec/changes/add-battery-lifetime/tas
|
||||
|
||||
Once 10.2 – 10.5 are observed in the live install, mark them in `tasks.md` and run `openspec archive --change "add-battery-lifetime"` (the OpenSpec workflow). The change has `isComplete: true` per `openspec status` (all artifacts are done; the open task checkboxes don't block archive).
|
||||
|
||||
### 3. Investigate the multi-minute initial-setup freeze
|
||||
### 3. ~~Investigate the multi-minute initial-setup freeze~~ — FIXED in v0.1.3
|
||||
|
||||
User reported that pressing **Submit** on the config dialog locked the UI for several minutes on a 70-device / 554-entity install. v0.1.1 warns about this in the dialog, but the underlying cause should be confirmed before considering it acceptable. Likely culprits:
|
||||
v0.1.3 ships the cold-start defer: `_ensure_record` schedules `_attempt_cold_start_backfill` via `hass.async_create_task` instead of awaiting it, so `async_setup` returns within the time bounded by the entity-registry scan (sub-second on the user's install). The coordinator tracks in-flight backfills in `_pending_backfills: set[str]` and fires one persistent notification (`battery_lifetime_cold_start_complete`) when the set drains.
|
||||
|
||||
- `_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.
|
||||
The dialog warning was softened from the bold/all-caps freeze warning to a calmer "background backfill may take several minutes; a notification will appear when complete" note in `strings.json` and `translations/en.json`.
|
||||
|
||||
**Worth observing on the live install after upgrade:** confirm that (a) re-adding the integration completes within seconds rather than minutes; (b) the `battery_lifetime_cold_start_complete` notification appears once the background backfill finishes; (c) the per-battery `replaced_on` values populate over the following minutes; (d) no regressions in the 70 → 554 entity registration.
|
||||
|
||||
### 4. Loose ends from earlier sessions
|
||||
|
||||
@@ -160,3 +158,4 @@ Ready to archive once 10.2 – 10.5 are observed live and the boxes are checked.
|
||||
### 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`.
|
||||
- `openspec/changes/archive/2026-05-11-defer-cold-start-backfill/` — v0.1.3 release. Same target spec; adds two requirements (Cold-start backfill is non-blocking; Backfill batch completion is announced exactly once).
|
||||
|
||||
@@ -186,6 +186,15 @@ functional throughout, and a one-time persistent notification ("Battery
|
||||
Lifetime: backfill complete") appears when the initial backfill batch is
|
||||
done.
|
||||
|
||||
## When a battery disappears
|
||||
|
||||
When a source battery is removed from Home Assistant (device deleted, Zigbee2MQTT un-paired, integration uninstalled), the integration:
|
||||
|
||||
1. Drops the in-memory state immediately. The eight companion entities flip to `unavailable` in the UI.
|
||||
2. **Soft-deletes** the persistent state in `.storage/battery_lifetime` — `replaced_on`, profile, threshold override, and EWMA state are kept against the chance of restore. The entry is stamped with a `removed_at` timestamp.
|
||||
3. If the same `unique_id` reappears within 30 days (e.g. you re-pair the device), the prior state is restored and the companion entities resume automatically — no UI rebuild, your `replaced_on` is preserved.
|
||||
4. After 30 days, the soft-deleted store entry is pruned, and the companion **device card plus all eight companion entities are removed** from Home Assistant's registry. No orphan `unavailable` rows linger.
|
||||
|
||||
## The forward-prediction service
|
||||
|
||||
```yaml
|
||||
|
||||
@@ -28,7 +28,7 @@ from homeassistant.core import (
|
||||
HomeAssistant,
|
||||
callback,
|
||||
)
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
from homeassistant.helpers.event import async_track_time_interval
|
||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
|
||||
|
||||
@@ -285,6 +285,30 @@ class BatteryLifetimeCoordinator(
|
||||
notification_id="battery_lifetime_cold_start_complete",
|
||||
)
|
||||
|
||||
def _purge_companions_for_pruned(self, unique_ids: list[str]) -> None:
|
||||
"""Remove the companion device for each pruned source.
|
||||
|
||||
HA's device-registry removal cascades to the entity registry and
|
||||
drops every entry tied to the device, which on the Battery Lifetime
|
||||
device card is exactly the eight per-source companion entries.
|
||||
Idempotent: a missing device is a silent no-op.
|
||||
"""
|
||||
if not unique_ids:
|
||||
return
|
||||
device_registry = dr.async_get(self.hass)
|
||||
for source_uid in unique_ids:
|
||||
device = device_registry.async_get_device(
|
||||
identifiers={(DOMAIN, source_uid)}
|
||||
)
|
||||
if device is None:
|
||||
continue
|
||||
device_registry.async_remove_device(device.id)
|
||||
_LOGGER.info(
|
||||
"battery_lifetime: removed orphan companion device for "
|
||||
"pruned source %s",
|
||||
source_uid,
|
||||
)
|
||||
|
||||
async def _attempt_cold_start_backfill(
|
||||
self, record: BatteryRecord
|
||||
) -> None:
|
||||
@@ -333,7 +357,10 @@ class BatteryLifetimeCoordinator(
|
||||
record = self._records.pop(unique_id, None)
|
||||
if record is not None:
|
||||
record.tracking_enabled = False
|
||||
self._store.prune_removed_older_than(REMOVED_SOURCE_RETENTION_DAYS)
|
||||
pruned = self._store.prune_removed_older_than(
|
||||
REMOVED_SOURCE_RETENTION_DAYS
|
||||
)
|
||||
self._purge_companions_for_pruned(pruned)
|
||||
return
|
||||
registry = er.async_get(self.hass)
|
||||
entry = registry.async_get(entity_id)
|
||||
@@ -554,7 +581,10 @@ class BatteryLifetimeCoordinator(
|
||||
|
||||
@callback
|
||||
def _handle_tick(self, _now: datetime) -> None:
|
||||
self._store.prune_removed_older_than(REMOVED_SOURCE_RETENTION_DAYS)
|
||||
pruned = self._store.prune_removed_older_than(
|
||||
REMOVED_SOURCE_RETENTION_DAYS
|
||||
)
|
||||
self._purge_companions_for_pruned(pruned)
|
||||
self.hass.async_create_task(self._async_recompute_and_maybe_publish())
|
||||
|
||||
async def _async_recompute_and_maybe_publish(self) -> None:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"domain": "battery_lifetime",
|
||||
"name": "Battery Lifetime",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.4",
|
||||
"documentation": "https://github.com/Falkvinge/hassio-integration-battery-lifetime",
|
||||
"issue_tracker": "https://github.com/Falkvinge/hassio-integration-battery-lifetime/issues",
|
||||
"codeowners": ["@rickfalkvinge"],
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-05-11
|
||||
@@ -0,0 +1,61 @@
|
||||
## Context
|
||||
|
||||
Each tracked battery is represented in HA by a per-source companion device whose identifier tuple is `(DOMAIN, source_unique_id)`. The eight companion entities (replace-by sensor, prediction-quality sensor, drain-rate sensor, two switches, button, date, number) all attach to that device via their `device_info` returned from `BatteryCompanionEntity.device_info`. When the source disappears, `_async_registry_changed`'s `action: remove` branch:
|
||||
|
||||
1. Pops `entity_id → unique_id` from `self._source_to_unique`.
|
||||
2. Soft-deletes the JSON-store entry (`store.remove_battery(unique_id)` stamps `removed_at = time.time()`; the rest of the persisted state — `replaced_on`, profile, threshold override, EWMA state — is retained against possible restore within 30 days).
|
||||
3. Pops the in-memory `BatteryRecord` from `self._records`. The companion entities' `available` property flips to `False` because `record` becomes `None`, so the eight entities show as `unavailable` in the UI immediately.
|
||||
4. Calls `prune_removed_older_than(REMOVED_SOURCE_RETENTION_DAYS)` to garbage-collect any *other* soft-deleted entries whose `removed_at` is older than 30 days.
|
||||
|
||||
The same `prune_removed_older_than` call also runs on every 10-minute heartbeat tick (`_handle_tick`), so the prune is in fact reasonably continuous — within ten minutes of crossing the 30-day threshold for any soft-deleted entry, the JSON store is cleaned up.
|
||||
|
||||
What's missing today: at the moment the JSON store actually drops a `unique_id`, the corresponding companion device + its eight entity-registry entries remain in HA's registry forever. They're orphan rows that the user must manually delete via Settings → Devices & Services → device card → ⋮ → Delete. Over a long-lived install with periodic battery-device churn (Z2M re-pairs, integration churn, sensor renames that change `unique_id`), this accumulates.
|
||||
|
||||
## Goals / Non-Goals
|
||||
|
||||
**Goals:**
|
||||
- When `prune_removed_older_than` actually removes a `unique_id` from the JSON store, the matching HA device entry (`identifiers={(DOMAIN, source_unique_id)}`) and all its child entity-registry entries are removed from the HA registry in the same code path.
|
||||
- The cleanup runs in both the on-remove-event path (`_async_registry_changed`) and the heartbeat path (`_handle_tick`), so cleanup happens as soon as the prune itself fires, regardless of which path triggered it.
|
||||
- The cleanup is idempotent: if the device is already gone (manually deleted, race with another integration, never created in the first place), the purge step is a no-op rather than an error.
|
||||
|
||||
**Non-Goals:**
|
||||
- Cleaning up legacy orphans accumulated before v0.1.4. Their JSON-store entries are already long pruned, so the new purge — which is keyed by the prune's return value — has nothing to act on for them. A separate one-shot "scan registry for our companion device entries with no matching JSON-store source" pass would be needed; deferred until/unless asked for.
|
||||
- Changing the 30-day retention window or the prune cadence. Those are governed by `REMOVED_SOURCE_RETENTION_DAYS` and `_handle_tick`'s timer respectively and are unaffected.
|
||||
- Direct entity-registry walks. HA's device-registry removal cascades the entity removals for us (see Decision 2).
|
||||
|
||||
## Decisions
|
||||
|
||||
### Decision 1: Purge by device, not by entity prefix
|
||||
|
||||
**Choice**: At purge time, look up the per-source companion device via `device_registry.async_get_device(identifiers={(DOMAIN, source_unique_id)})`. If found, call `device_registry.async_remove_device(device.id)`. HA's device-registry removal cascades to the entity registry, which removes all entity entries tied to that device. Since the Battery Lifetime device card is exclusively owned by this integration's eight companion entities (the source battery has its *own* device, separate from ours), the cascade removes exactly what we want.
|
||||
|
||||
**Alternatives considered**:
|
||||
- *Walk entity registry, match by `unique_id` prefix `battery_lifetime:<source_uid>:`*: works but is O(N entities) per purge and duplicates the device-registry's cascade machinery. We'd still need to clean up the device entry separately to avoid an empty-card orphan. Rejected as more code for less cleanup.
|
||||
- *Iterate the eight known suffixes and look up by exact companion `unique_id`*: brittle to suffix additions/renames. Rejected.
|
||||
|
||||
### Decision 2: Trust HA's device-removal cascade rather than walking the entity registry
|
||||
|
||||
**Choice**: After `async_remove_device(device_id)`, do not separately walk the entity registry to confirm the entries are gone. HA fires `device_registry_updated` (with `action: remove`) on device removal, and the entity registry has its own listener that removes child entities. This is HA-core behavior and is relied upon by every standard integration.
|
||||
|
||||
**Alternative considered**: belt-and-braces walk after the device removal. Rejected — adds code for no real benefit, and would mask if HA ever changed the cascade behavior (which would be a regression we'd want to surface, not paper over).
|
||||
|
||||
### Decision 3: Purge only after a successful prune, never speculatively
|
||||
|
||||
**Choice**: The purge is keyed off `prune_removed_older_than`'s return value (the list of `unique_id`s it actually dropped). Soft-deleted entries within their grace window are never touched. An entry that's still in the store but has `removed_at != None` is recoverable (via `store.restore_battery`) and its companion device + entities are still intact (they're just `unavailable`); restoring within the window resurrects the user's previous configuration with no UI rebuild needed.
|
||||
|
||||
This means: the new behavior is invisible until the 30-day grace window elapses for some real source. For the user's live install, no immediate UI change after the v0.1.4 upgrade.
|
||||
|
||||
## Risks / Trade-offs
|
||||
|
||||
- **Risk**: A user has manually deleted the device entry already (e.g. cleaned up an orphan via the UI yesterday) but the corresponding store entry hasn't yet been pruned. → Mitigation: `async_get_device` returns `None`, the purge step is a no-op for that source. No error, no warning needed.
|
||||
- **Risk**: A user has manually re-added entities to our device card (e.g. via customize, or an automation that pinned an entity to our device). On purge, those would also be cascaded out. → Mitigation: practically impossible — HA's customize doesn't let you reparent entities to arbitrary devices, and our device identifiers are a tuple opaque to other integrations. If someone has truly done this, they can re-add post-purge; this risk is theoretical.
|
||||
- **Risk**: HA removes the device-removal cascade or changes its semantics. → Mitigation: covered by tests; would surface as a regression rather than silent dust accumulation.
|
||||
- **Trade-off**: Pre-existing orphans (sources removed before v0.1.4) are not cleaned up by this change. Acceptable because: (a) the user's current install only has them if some battery has actually been deleted in the past — observable, finite, and manually fixable; (b) bolting on a one-shot legacy scanner risks racing with the brand-new install's own platform-forward setup; (c) keeping this change small makes it easy to review and easy to ship.
|
||||
|
||||
## Migration Plan
|
||||
|
||||
No migration required. Persistent state in `.storage/battery_lifetime` is unchanged. After in-place upgrade via HACS, any source whose grace window expires (now or in the future) gets its companion device + entities cleaned up automatically. No user action needed.
|
||||
|
||||
## Open Questions
|
||||
|
||||
None.
|
||||
@@ -0,0 +1,30 @@
|
||||
## Why
|
||||
|
||||
When a tracked battery's source entity is removed from Home Assistant (device deleted, integration uninstalled, Z2M un-paired), the coordinator soft-deletes the JSON-store entry and the in-memory `BatteryRecord`, and after `REMOVED_SOURCE_RETENTION_DAYS = 30` the JSON entry is hard-deleted by `BatteryLifetimeStore.prune_removed_older_than`. But the eight HA entity-registry entries for the per-source companion entities (`sensor.<src>_replace_by`, `..._prediction_quality`, `..._drain_rate`, `switch.<src>_profile_lithium`, `..._tracking_enabled`, `button.<src>_mark_replaced`, `date.<src>_replaced_on`, `number.<src>_threshold_override`) plus the per-source companion device entry (`identifiers={(DOMAIN, source_unique_id)}`) are never removed. They stay in HA's registry indefinitely as `unavailable` orphans, and the user has to garbage-collect them manually via Settings → Devices & Services.
|
||||
|
||||
This is the moment where "the integration knows the source is gone for good" actually arrives — `prune_removed_older_than` returns the list of `unique_id`s it just dropped from the store. Cleaning up the corresponding companion device at that point is cheap, well-bounded, and matches user expectation.
|
||||
|
||||
## What Changes
|
||||
|
||||
- The coordinator SHALL purge each pruned source's companion device from Home Assistant's device registry whenever `prune_removed_older_than` returns a non-empty list. Removing the device is sufficient: HA's device-registry removal cascades to all entity-registry entries tied to that device, which on the Battery Lifetime device card means exactly the eight per-source companion entries.
|
||||
- The two existing call sites that drive prune (`_async_registry_changed` on `action: remove`, and `_handle_tick` on every 10-minute heartbeat) SHALL feed the pruned list into the new purge step. No new call sites; no change to prune timing or the 30-day retention window.
|
||||
|
||||
Out of scope: legacy orphans accumulated before v0.1.4 are not retroactively cleaned up. Their JSON-store entries are already gone (so the new purge has no `unique_id` to act on), but their HA registry entries linger. Users can either delete them manually via the UI today, or wait for a future explicit "cleanup pre-existing orphans" pass if this becomes a real pain point. Not adding it now to keep the diff focused on the user's request.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
(none)
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `coordinator-scheduling`: adds a "Pruned sources have their companion device removed" requirement governing the cleanup step that runs after every prune.
|
||||
|
||||
## Impact
|
||||
|
||||
- `custom_components/battery_lifetime/coordinator.py`: add `_purge_companions_for_pruned(unique_ids)` helper; update both prune call sites to capture the return value and pass it to the purge.
|
||||
- `custom_components/battery_lifetime/manifest.json`: version bump to `0.1.4`.
|
||||
- `tests/test_coordinator.py`: two new tests — one direct on the purge helper, one end-to-end driving through a registry-remove + forced-old prune.
|
||||
- `README.md`: short note in the existing removal/restore narrative (or a "v0.1.4 cleanup" sentence in the cold-start section, depending on what reads cleanest).
|
||||
- No new runtime dependencies. No schema migration. No public service or event payload changes. No breaking changes for existing installs.
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Pruned sources have their companion device removed
|
||||
|
||||
When `BatteryLifetimeStore.prune_removed_older_than(REMOVED_SOURCE_RETENTION_DAYS)` returns a non-empty list of pruned source `unique_id`s, the coordinator SHALL look up the per-source companion device in HA's device registry by `identifiers={(DOMAIN, source_unique_id)}` and, if found, call `device_registry.async_remove_device(device.id)` for each pruned `unique_id`. HA's device-registry removal cascades to the entity registry and removes all entries tied to that device, which on the Battery Lifetime device card is exactly the eight per-source companion entries (`*_replace_by`, `*_prediction_quality`, `*_drain_rate`, `*_profile_lithium`, `*_tracking_enabled`, `*_mark_replaced`, `*_replaced_on`, `*_threshold_override`).
|
||||
|
||||
The cleanup SHALL run in both prune call sites:
|
||||
- `_async_registry_changed` on `action: remove` (after the soft-delete + prune sweep).
|
||||
- `_handle_tick` on every periodic heartbeat (after the prune sweep).
|
||||
|
||||
The cleanup SHALL be idempotent: looking up a device that does not exist (already manually removed, or never created because the source was removed before any platform forward completed) SHALL be a silent no-op.
|
||||
|
||||
The cleanup SHALL NOT run for soft-deleted entries that are still within their 30-day grace window. Those remain recoverable via `store.restore_battery`, and their companion devices and entities remain in the HA registry (showing `unavailable`) so that restore re-enables them without rebuilding the UI.
|
||||
|
||||
#### Scenario: Source pruned past the grace window has its device removed
|
||||
- **WHEN** a source battery is removed from the entity registry, then enough time passes that its `removed_at` is older than `REMOVED_SOURCE_RETENTION_DAYS` (30 days), then the coordinator's heartbeat runs and `prune_removed_older_than` returns the source's `unique_id` in its drop list
|
||||
- **THEN** the corresponding device entry with `identifiers={(DOMAIN, source_unique_id)}` is no longer present in HA's device registry, and the eight per-source companion entries are no longer present in HA's entity registry
|
||||
|
||||
#### Scenario: Source removed but still within grace window keeps its device
|
||||
- **WHEN** a source battery is removed from the entity registry and the next heartbeat fires within the 30-day retention window
|
||||
- **THEN** the prune returns an empty list for this source, the device entry remains in the registry, the eight companion entries remain in the registry showing `unavailable`, and a subsequent `store.restore_battery(unique_id)` call (e.g. because the source reappeared) re-enables the entities without rebuilding them
|
||||
|
||||
#### Scenario: Purge of a source whose device was already manually removed is a no-op
|
||||
- **WHEN** `prune_removed_older_than` returns a `unique_id` for which the user has already manually deleted the companion device via the HA UI
|
||||
- **THEN** `device_registry.async_get_device(identifiers={(DOMAIN, source_unique_id)})` returns `None`, the purge step is a silent no-op for that source, and no error is logged
|
||||
@@ -0,0 +1,28 @@
|
||||
## 1. Coordinator: purge orphan companion devices on prune
|
||||
|
||||
- [x] 1.1 Imported `device_registry as dr` in `coordinator.py`.
|
||||
- [x] 1.2 Added `_purge_companions_for_pruned(self, unique_ids: list[str]) -> None`. Idempotent on missing device; logs at info level when a device is actually removed.
|
||||
- [x] 1.3 Captured the return value of `prune_removed_older_than` in `_async_registry_changed` and fed it to the purge.
|
||||
- [x] 1.4 Same in `_handle_tick`.
|
||||
|
||||
## 2. Tests
|
||||
|
||||
- [x] 2.1 `test_purge_companions_for_pruned_removes_device` — uses `MockConfigEntry` to satisfy `device_registry.async_get_or_create`'s `config_entry_id` requirement; pre-creates the device, calls the purge, asserts gone.
|
||||
- [x] 2.2 `test_purge_companions_for_pruned_is_noop_for_missing_device` — calls with a never-existed unique_id and with `[]`. No exception, no notification.
|
||||
- [x] 2.3 `test_remove_event_chain_purges_after_grace_window` — full chain. Forges `removed_at` directly via `store._data["batteries"]["uid-foo"]["removed_at"] = time.time() - (REMOVED_SOURCE_RETENTION_DAYS + 1) * 86400` to fast-forward the 30-day clock without monkey-patching `time.time`. Drives `_handle_tick` to trigger prune+purge. Asserts both store entry and device entry gone.
|
||||
|
||||
## 3. Release plumbing
|
||||
|
||||
- [x] 3.1 Bumped `manifest.json` `version` to `0.1.4`.
|
||||
- [x] 3.2 Added "When a battery disappears" section to `README.md` documenting the soft-delete + 30-day restore window + auto-purge lifecycle.
|
||||
- [x] 3.3 Full test suite green: 118 passed (115 prior + 3 new).
|
||||
|
||||
## 4. Close-out (executed from main checkout, not the worktree)
|
||||
|
||||
- [x] 4.1 Committed implementation on `agent/autoclean-orphan-companion-entities` (commit 13b3dd6).
|
||||
- [ ] 4.2 Merge `agent/autoclean-orphan-companion-entities` into `master` via the main checkout (`git merge --no-ff`).
|
||||
- [ ] 4.3 Push `master` to both `origin` (gitea) and `github`; push tag `v0.1.4` to both.
|
||||
- [ ] 4.4 Create GitHub release `v0.1.4` via `gh release create`.
|
||||
- [ ] 4.5 Sync the delta into `openspec/specs/coordinator-scheduling/spec.md` and archive the change.
|
||||
- [ ] 4.6 Remove the worktree and branch.
|
||||
- [ ] 4.7 Update `HANDOFF.md` to reflect v0.1.4 shipped.
|
||||
@@ -45,3 +45,31 @@ On each periodic heartbeat the coordinator SHALL recompute every record's `Predi
|
||||
#### 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
|
||||
|
||||
### 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
|
||||
|
||||
+111
-1
@@ -8,7 +8,7 @@ from typing import Any
|
||||
import pytest
|
||||
from homeassistant.components.sensor import SensorDeviceClass
|
||||
from homeassistant.const import PERCENTAGE
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
|
||||
from custom_components.battery_lifetime.const import DOMAIN
|
||||
from custom_components.battery_lifetime.coordinator import (
|
||||
@@ -542,6 +542,116 @@ async def test_no_pending_backfill_no_notification(hass: Any) -> None:
|
||||
await coord.async_shutdown()
|
||||
|
||||
|
||||
async def test_purge_companions_for_pruned_removes_device(hass: Any) -> None:
|
||||
"""A pruned source's companion device is removed from the device registry."""
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
entry = MockConfigEntry(domain=DOMAIN, unique_id=DOMAIN)
|
||||
entry.add_to_hass(hass)
|
||||
device_registry = dr.async_get(hass)
|
||||
device = device_registry.async_get_or_create(
|
||||
config_entry_id=entry.entry_id,
|
||||
identifiers={(DOMAIN, "uid-foo")},
|
||||
manufacturer="Battery Lifetime",
|
||||
name="Battery: sensor.foo_battery",
|
||||
)
|
||||
assert (
|
||||
device_registry.async_get_device(identifiers={(DOMAIN, "uid-foo")})
|
||||
is not None
|
||||
)
|
||||
|
||||
store = BatteryLifetimeStore(hass)
|
||||
await store.async_load()
|
||||
coord = BatteryLifetimeCoordinator(hass, store=store)
|
||||
coord._purge_companions_for_pruned(["uid-foo"])
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (
|
||||
device_registry.async_get_device(identifiers={(DOMAIN, "uid-foo")})
|
||||
is None
|
||||
)
|
||||
await coord.async_shutdown()
|
||||
|
||||
|
||||
async def test_purge_companions_for_pruned_is_noop_for_missing_device(
|
||||
hass: Any,
|
||||
) -> None:
|
||||
"""Purging a unique_id with no device entry is a silent no-op."""
|
||||
store = BatteryLifetimeStore(hass)
|
||||
await store.async_load()
|
||||
coord = BatteryLifetimeCoordinator(hass, store=store)
|
||||
|
||||
coord._purge_companions_for_pruned(["uid-never-existed"])
|
||||
coord._purge_companions_for_pruned([])
|
||||
await hass.async_block_till_done()
|
||||
await coord.async_shutdown()
|
||||
|
||||
|
||||
async def test_remove_event_chain_purges_after_grace_window(hass: Any) -> None:
|
||||
"""Once the 30-day grace elapses, the next prune drives a device purge.
|
||||
|
||||
Exercises the full _async_registry_changed -> store.prune -> purge chain
|
||||
by forging an old removed_at directly so prune actually removes the
|
||||
entry (without waiting 30 days of wall clock).
|
||||
"""
|
||||
import time as _time
|
||||
from pytest_homeassistant_custom_component.common import MockConfigEntry
|
||||
|
||||
from custom_components.battery_lifetime.const import (
|
||||
REMOVED_SOURCE_RETENTION_DAYS,
|
||||
)
|
||||
|
||||
entry = MockConfigEntry(domain=DOMAIN, unique_id=DOMAIN)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
registry = er.async_get(hass)
|
||||
_register(registry, entity_id="sensor.foo_battery", unique_id="uid-foo")
|
||||
hass.states.async_set("sensor.foo_battery", "84", {})
|
||||
|
||||
device_registry = dr.async_get(hass)
|
||||
device_registry.async_get_or_create(
|
||||
config_entry_id=entry.entry_id,
|
||||
identifiers={(DOMAIN, "uid-foo")},
|
||||
manufacturer="Battery Lifetime",
|
||||
name="Battery: sensor.foo_battery",
|
||||
)
|
||||
|
||||
store = BatteryLifetimeStore(hass)
|
||||
await store.async_load()
|
||||
coord = BatteryLifetimeCoordinator(hass, store=store)
|
||||
await coord.async_setup()
|
||||
await hass.async_block_till_done()
|
||||
assert "uid-foo" in coord.records
|
||||
|
||||
hass.bus.async_fire(
|
||||
"entity_registry_updated",
|
||||
{"action": "remove", "entity_id": "sensor.foo_battery"},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
assert "uid-foo" not in coord.records
|
||||
stored = store.get_battery("uid-foo")
|
||||
assert stored is not None
|
||||
assert stored.get("removed_at") is not None
|
||||
assert (
|
||||
device_registry.async_get_device(identifiers={(DOMAIN, "uid-foo")})
|
||||
is not None
|
||||
)
|
||||
|
||||
store._data["batteries"]["uid-foo"]["removed_at"] = (
|
||||
_time.time() - (REMOVED_SOURCE_RETENTION_DAYS + 1) * 86400
|
||||
)
|
||||
|
||||
coord._handle_tick(datetime.now(tz=UTC))
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert store.get_battery("uid-foo") is None
|
||||
assert (
|
||||
device_registry.async_get_device(identifiers={(DOMAIN, "uid-foo")})
|
||||
is None
|
||||
)
|
||||
await coord.async_shutdown()
|
||||
|
||||
|
||||
async def test_source_without_unique_id_logged_and_skipped(
|
||||
hass: Any, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
|
||||
Reference in New Issue
Block a user