Skip to content

fix: also rename entity_id when migrating p_grid_out → grid_power#124

Merged
dewet22 merged 1 commit into
mainfrom
fix/entity-id-migration-grid-power
Jun 4, 2026
Merged

fix: also rename entity_id when migrating p_grid_out → grid_power#124
dewet22 merged 1 commit into
mainfrom
fix/entity-id-migration-grid-power

Conversation

@dewet22

@dewet22 dewet22 commented Jun 4, 2026

Copy link
Copy Markdown
Owner

Problem

_migrate_unique_ids updated the unique_id (e.g. {serial}_p_grid_out{serial}_grid_power) but not the entity_id. On installs where the sensor was first registered under its original "Grid Export Power" name, the entity_id remained sensor.givenergy_inverter_{serial}_grid_export_power. The dashboard generator constructs sensor.givenergy_inverter_{serial}_grid_power — that entity_id doesn't exist, producing widespread "Entity not available" errors on v1.1.3rc1+. Grid power appears in the power-flow overview, 24-hour chart, and today chart, so most of the dashboard fails.

Fix

Widen _RENAMED_UNIQUE_ID_SUFFIXES values from plain strings to (new_suffix, old_entity_slug | None) tuples. When old_entity_slug is set and the existing entity_id ends with that slug, pass new_entity_id to async_update_entity alongside new_unique_id. The other three renames (e_load_day, e_inverter_out_day, e_inverter_out_total) carry None for the slug — no behaviour change for them.

A regression test verifies that after setup an entity registered under the old unique_id and the old _grid_export_power entity_id is found at _grid_power with the updated unique_id.

Test plan

  • uv run pytest — 242 passed
  • Deploy to HACS as a new rc and confirm sensor.givenergy_inverter_{serial}_grid_power appears carrying old history; dashboard power-flow, 24h chart and today chart all render

Summary by CodeRabbit

  • New Features
    • Enhanced entity migration to automatically rename and coordinate entity identifiers alongside unique ID updates, ensuring proper consistency during integration upgrades.

_migrate_unique_ids updated the unique_id but not the entity_id. On
installs that registered the sensor under its original 'Grid Export Power'
name, the entity_id remained …_grid_export_power while the dashboard
generator constructed …_grid_power references — causing widespread
'Entity not available' errors on v1.1.3rc1+.

Widen _RENAMED_UNIQUE_ID_SUFFIXES values to (new_suffix, old_entity_slug)
tuples. When old_entity_slug is set and the entity_id ends with that slug,
pass new_entity_id to async_update_entity alongside new_unique_id.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 4, 2026

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

Pull request was closed or merged during review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 509b4793-12f6-495c-a164-0c23ad154723

📥 Commits

Reviewing files that changed from the base of the PR and between 366096e and e8f53dd.

📒 Files selected for processing (2)
  • custom_components/givenergy_local/__init__.py
  • tests/test_sensor.py

📝 Walkthrough

Walkthrough

The PR enhances the GivEnergy integration's entity migration system to coordinately rename both unique_id and entity_id for renamed sensors. The migration mapping now stores optional prior entity-id slugs alongside new unique-id suffixes, enabling the migration logic to detect and rewrite old entity-ids when they match the stored slug, with corresponding test coverage.

Changes

Entity Migration Enhancements

Layer / File(s) Summary
Enhanced migration mapping structure
custom_components/givenergy_local/__init__.py
The _RENAMED_UNIQUE_ID_SUFFIXES mapping is enriched to pair each old suffix with both a new suffix and an optional prior entity_id slug, enabling conditional entity_id rewrites during migration.
Migration logic with entity_id rewriting
custom_components/givenergy_local/__init__.py
The _migrate_unique_ids function now computes an optional new_entity_id by rewriting the existing entity_id when a prior slug is provided and matches, logs both old/new entity_ids when applicable, and conditionally passes new_entity_id to the entity registry update.
Test for grid_export_power entity_id migration
tests/test_sensor.py
A new test creates an entity with the old p_grid_out unique_id and manually sets its entity_id to the historical grid_export_power slug, then verifies that after integration setup the old entity_id is removed and the migrated sensor exists under the new grid_power entity_id with the correct unique_id.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • dewet22/givenergy-hass#111: Both PRs modify custom_components/givenergy_local/__init__.py's entity registry migration logic for givenergy-modbus v2.1.1 renamed unique_id suffixes (with the main PR extending it to also realign entity_id).
  • dewet22/givenergy-hass#113: Both PRs touch the integration's unique-id migration mechanism in custom_components/givenergy_local/__init__.pyfeat: rename inverter-output pair to PV Generation + modbus 2.1.2 #113 extends _RENAMED_UNIQUE_ID_SUFFIXES for inverter-output→PV generation suffix remaps, while the main PR updates _migrate_unique_ids to also support coordinated entity_id renames.

Suggested reviewers

  • dewet22-codex

Poem

🐰 A hop through migration's lane,
Old slugs and IDs now refrain—
grid_export_power bids adieu,
To grid_power's fresh debut!
With mapping and logic aligned just right,
Entities migrate smooth as a flight. 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: fixing entity_id renaming during the p_grid_out to grid_power migration.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/entity-id-migration-grid-power

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@deepsource-io

deepsource-io Bot commented Jun 4, 2026

Copy link
Copy Markdown

DeepSource Code Review

We reviewed changes in 366096e...e8f53dd on this pull request. Below is the summary for the review, and you can see the individual issues we found as inline review comments.

See full review on DeepSource ↗

PR Report Card

Overall Grade   Security  

Reliability  

Complexity  

Hygiene  

Code Review Summary

Analyzer Status Updated (UTC) Details
Python Jun 4, 2026 7:57a.m. Review ↗

Important

AI Review is run only on demand for your team. We're only showing results of static analysis review right now. To trigger AI Review, comment @deepsourcebot review on this thread.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request modifies the entity migration logic to rename the entity_id in addition to the unique_id when migrating specific sensors, such as renaming grid_export_power to grid_power. However, the reviewer points out that renaming the entity_id during migration can break user automations, scripts, and templates. They recommend preserving the existing entity_id and only updating the unique_id.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +403 to +418
new_entity_id = (
ent.entity_id[: -len(old_slug)] + new
if old_slug and ent.entity_id.endswith(f"_{old_slug}")
else None
)
_LOGGER.info(
"Migrating unique_id %s -> %s%s",
ent.unique_id,
new_uid,
f" (entity_id: {ent.entity_id} -> {new_entity_id})" if new_entity_id else "",
)
registry.async_update_entity(
ent.entity_id,
new_unique_id=new_uid,
**({"new_entity_id": new_entity_id} if new_entity_id else {}),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

When performing entity migrations in Home Assistant, we must preserve the existing entity_id and only update the unique_id. Renaming the entity_id can break user automations, scripts, and templates that reference the old entity ID. Please update the migration logic to only modify the unique_id and leave the entity_id unchanged.

            _LOGGER.info(
                "Migrating unique_id %s -> %s",
                ent.unique_id,
                new_uid,
            )
            registry.async_update_entity(
                ent.entity_id,
                new_unique_id=new_uid,
            )
References
  1. When performing entity migrations in Home Assistant, preserve the existing entity_id and only update the unique_id to prevent breaking user automations and templates that reference the old entity ID.

@dewet22 dewet22 merged commit 570d50c into main Jun 4, 2026
9 of 10 checks passed
@dewet22 dewet22 deleted the fix/entity-id-migration-grid-power branch June 4, 2026 07:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant