HA Restart or Template Entities Reload Increments history_stats

I have seen a couple of topics on this (all are old), and a couple of HA GitHub issues (Oct 2022, Nov 2023) closed with no answer.

I am trying to understand how to prevent a history_stats sensor from incrementing when its state is true (in this case “ON”) and HA is restarted or Template Entities are reloaded.

Here is a simple example from one of my HA package YAML files:

template:
  # ---------------------------------------------------------------------------
  # This binary sensor will monitor if the sun is down
  # ---------------------------------------------------------------------------
  - binary_sensor:
      - name: Sample - Sun is down
        unique_id: sample_sun_is_down
        # If the washing machine is consuming more than the set Watts
        state: >
          {{ is_state("sun.sun", "below_horizon") }}

sensor:
  # ---------------------------------------------------------------------------
  # This history_stats sensor counts how many times the sun goes down per day
  # ---------------------------------------------------------------------------
  - platform: history_stats
    name: History - Sun Is Down Counter
    unique_id: history_sun_is_down_counter
    entity_id: binary_sensor.sample_sun_is_down
    state: "on"
    type: count
    start: "{{ now().replace(hour=0, minute=0, second=0) }}"
    duration:
      hours: 24

Here are some simple steps to recreate what I am seeing:

  1. Create this binary_sensor and history_stats sensor in your YAML.
  2. Restart HA and visit the Developer ToolsStates section
  3. Filter the entities on “sun_is_down” and see the two sensors created above.
  4. If the sun is in fact down, the binary_sensor.sample_sun_is_down entity will be in the on state
  5. The sensor.history_sun_is_down_counter should be at zero (0)
  6. Restart HA or reload Template Entities in a separate window and watch the binary_sensor.sample_sun_is_down entity increment.

Weird, who knew the sun could go down so many times a day?

My theory:

On a HA Restart or Template Entities Reload, the binary_sensor.sample_sun_is_down momentarily switches to undefined during the restart and back to on and gets counted by the history_stats` sensor

My Question:

How can this be prevented? Is this a bug in the history_stats sensor?