New behavior: self-referencing template is evaluated twice?

I have a couple places where I need the N latest values of a sensor.

However, in very recent HA versions I noticed that self-referencing templates suddenly seem to be evaluated twice. For example:

template:
  - unique_id: my_meter
    trigger:
      - platform: webhook
        webhook_id: my-webhook-id
        local_only: true
    sensor:
      - name: "My meter: power history"
        unique_id: my_meter_power_history
        state: "{{ ([ now().timestamp()|int, trigger.json['mykey']|float ] + this.state.split('|'))[:8]|join('|') }}"

With this, I would expect the state to be (with added spaces for readability):
timestampN | valueN | timestampN-1 | valueN-1 | timestampN-2 | valueN-2 | timestampN-3 | valueN-3

But instead I’m getting:
timestampN | valueN | timestampN | valueN | timestampN-1 | valueN-1 | timestampN-1 | valueN-1

From what I see, the state is evaluated twice because of the self-reference.
In the states database, I also see each state listed twice (within a few milliseconds).
It appears that the state is evaluated twice with the same context (eg: trigger.id, trigger.json are the same) but haven’t looked further.

Of course the Webhook is only called once. And as soon as I remove the self-reference, the double evaluation vanishes.

Anyone noticed this? This seems to be specific to recent HA versions.

And of course the inevitable question: how can I self-reference the previous value of a template, without it being evaluated a 2nd time afterwards?

Welcome MatrixRewriter,

I’m also experiencing this issue, see here: List entries within an attribute are processed twice · Issue #99972 · home-assistant/core · GitHub

Hi @pedolsky,
Thanks! I’ve cross-linked this topic from yours as well.

An additional thing that I found: adding a random() statement to the template confirms that the value is fully evaluated twice (with 2 different values of random).

1 Like

Looks like Taras (123) has posted a workaround in that issue that you can use until it is fixed.

Thank you, Tom_I. He also posted the workaround on Github.

Workaround

Didn’t know that it’s possible to reference the keys as attribute.

Ha, yep that was the one I meant.

Ask about the attributes in the issue, Taras should be subscribed to it.

Problem resolved for me with the latest Docker image (2023.9.2) pulled on 2023-09-13.
Note: this version is not on the changelog page yet.

Yep, can confirm. Updated this morning to 2023.9.2 Supervised and was pleased :blush:

fyi: Fix TriggerEntity.async_added_to_hass by emontnemery · Pull Request #100119 · home-assistant/core · GitHub was the fix