What is the best way to handle breaking changes to sensors?

I’m working on a new integration so I make fixes or just change my mind about the best way to expose something fairly regularly. When I do that anyone running the integration sees the left over sensors etc. and has to manually delete them. In some cases the sensors collide on identity and HA automatically adds and _2 and in my experience of trying to clean that up by deleting the dead original and renaming the new sensor, it seems to persist knowledge and sometimes repetitively re-duplicates the sensor going forward. I’ve also had reports that renaming the device sometimes results in the entire device being duplicated but I haven’t been able to reproduce this myself yet.

I’m looking for a couple of pieces of advice:

  • Is there a way / pattern to allow me to clean up dead/deprecated sensors?
  • What might I be messing up that’s causing that duplicated device issue?

Code is at:
greghesp/ha-bambulab: A Home Assistant Integration for Bambu Lab Printers (github.com)

Did the unique id’s change?

For device rename repro, no. The unique ids are fixed in code and generated from unchanging data (device serials).

Other cases, yes - that’s why I’m wondering what I can do make upgrades cleaner for folk. Most of the sensors are setup with:
self.attr_unique_id = f"{printer.serial}{description.key}"

In one case I had a typo in the key so the unique id changed which generated a new sensor and orphaned the old one as expected. But even after deleting the dead sensor the duplication seemed to keep coming back somehow. I never worked out what was going on before the point where I removed and re-added the integration and lost that repro. I don’t think that was an example of the _2 case though since I changed the key.

Look in .storage/core.config_entries and see what the difference is between the original and _2 entry.

In my case it was a changed unique id. You might need to call async_update_entity if it’s something else.

In the case where I need to change a unique ID (e.g. the typo example), is there a way I can automate removal of the orphaned entity?