Cannot re-add a device - foreign key constraint violation

I have two Aqara P1 motion sensors also known as lumi.sensor_motion.aq2.

I added both via ZHA and they worked fine at first. Then one of them dropped off the network, so I went through removing the device and attempting to re-add it.

This doesn’t work: the device is always registered with inaccessible entities and it doesn’t actually work any more. I’ve tried it many times.

If I inspect any of its entities, the warning This entity is unavailable is displayed.

In the logs, I noticed this line:

<timestamp> DEBUG (MainThread) [zigpy.appdb] Error handling '_save_attribute' event with (<IEEE redacted>, 1, 0, 5, 'lumi.sensor_motion.aq2', datetime.datetime(...)) params: FOREIGN KEY constraint failed

Has my Zigbee database become messed up?

How do I repair this?

Does anyone know how to make progress with this?

It looks like no-one knows how to fix this.

Is there a better way to ask for help from the developers?