How to prevent z-wave switch from getting out of sync

I have one particular z-wave Leviton switch where the state of the switch sometimes gets out of sync with what Home Assistant thinks the state is. As a consequence when my pyscript automation decides to turn off the switch (which controls a fan), HA seems to think the switch is already off, so no command gets to the switch and it just stays running forever. Or when my script asks HA what the state is, it gets a wrong answer and then makes wrong decisions. End, result, the fan runs forever until a human notices it.

Apparently the state got out of sync when some z-wave command failed to get delivered and sure enough I can see a couple failed transmissions.

I don’t know much about z-wave, but is there any way in the z-wave sub-system to require delivery confirmation of commands sent before HA updates its internal state? Or how else do I prevent this situation where HA’s cached state is out of sync with the actual switch state?

Periodically refresh the switch state. Don’t refresh too often. Every 10 minutes is reasonable.

Here’s an example from my system.

- id: "basement_light_1 poll switch state"
  alias: basement_light_1 poll switch
  description: "Automation to periodically poll switches"
  mode: single
  max_exceeded: silent
  trigger:
    - platform: time_pattern
      minutes: "9"
    - platform: time_pattern
      minutes: "39"
  action:
    - service: zwave_js.refresh_value
      data:
        entity_id: switch.basement_light_1
        refresh_all_values: false

you may try reinterviewing the switch. not syncing state is a sign that lifeline group missing, connection issues or other problem generally.

what do the devices stats show in device info?