evcc icon indicating copy to clipboard operation
evcc copied to clipboard

Solar forecast doubles after midnight (stale rates in mergeRatesAfter)

Open 1va13n7in opened this issue 4 months ago • 3 comments

Describe the bug

If one of several solar forecast tariffs only ever covers tomorrow (rolling one-day window, e.g. the Solcast HA integration's "forecast tomorrow" sensor), the combined solar forecast reports ~2x for the entire current day:

  1. tariff/helper.go mergeRatesAfter keeps existing rates with End <= newStart && End > now.
  2. For a tomorrow-only source, newStart is always tomorrow 00:00. So after midnight, the rates it fetched yesterday (describing what is now today) are retained all day and can never be refreshed.
  3. tariff/combined.go sums the fresh "today" source plus this stale copy: every slot of the current day is doubled.

This is hard to diagnose: no duplicate timestamps in /api/tariff/solar (summation already merged them), the stale part is frozen so the ratio drifts around 2.0, the UI's actual/forecast adjustment partially masks it, and a restart clears it until the next midnight, so it looks intermittent.

The retention itself is correct for price tariffs: tomorrow's day-ahead prices must not wipe today's still-valid ones. A solar forecast has no stale-but-valid data: yesterday's forecast for today is superseded, not complementary. The bug is the combination of merge retention, summation, and a rolling per-day source.

Evidence (live system, 15-min snapshot cron, no evcc restart involved)

Local time "today" sensor "tomorrow" sensor /api/tariff/solar peak for Jul 25
Jul 24 23:45 Jul 24 data Jul 25: 21.44 kW 23.50 kW (single)
Jul 25 00:00 Jul 25: 21.44 kW Jul 26: 15.99 kW 23.50 kW (no fetch since rollover)
Jul 25 00:15 Jul 25: 21.44 kW Jul 26: 15.99 kW 44.77 kW (doubled)

Cross-checks: tomorrow's slots stay single all night (only one source covers them); after a Solcast update (today 21.44 -> 22.19 kW) the doubled peak rose only by the fresh delta (44.77 -> 45.47 kW), i.e. the stale part cannot update; zero duplicate start values in the endpoint output at any time. Full capture series available on request.

Who is affected

Any setup feeding per-day sensors as separate solar tariffs. The Solcast HA integration exposes exactly this today/tomorrow sensor pair, HA-fed forecasts are a recurring pattern (e.g. #21882), and the pending HA tariff plugin (#27645) could inherit this if rolling per-day sensors are fetched individually.

Verified workaround

One combined source instead of two: a HA template sensor concatenates both detailedForecast attributes, evcc uses a single custom tariff against it. Fresh data then always starts at today 00:00 and the merge replaces the full future range. Three consecutive midnights verified clean (current-day peak stable across 00:00 -> 00:15).

Suggestions (for discussion)

  1. Solar forecast tariffs: replace all future rates on each successful fetch instead of merging; keep retention for price tariffs.
  2. And/or a docs note: one source per physical plant, covering its full horizon (Solcast today/tomorrow pair as the concrete anti-pattern).

Version

Observed on 0.311.1 (custom build 0.311.1-4-gf50cf5373). The responsible code path is unmodified: tariff/helper.go and tariff/combined.go are byte-identical to current master (diff empty; local commits touch the meter/optimizer pipeline only, one is the already-merged #32094). Mechanism additionally verified against current master source.

Root cause analysis was done over several days in collaboration with an AI assistant (Anthropic's Claude); all evidence was captured on the live system.

Steps to reproduce

Two custom forecast tariffs against rolling per-day sources (today / tomorrow, e.g. Solcast HA sensors), run across midnight, compare /api/tariff/solar against the "today" source: current day doubled from the first fetch after midnight, next day correct.

Solar config used (tokens redacted)
solar:
  - type: custom            # Solcast via HA -- today
    interval: 15m
    forecast:
      source: http
      uri: https://homeassistant.local/api/states/sensor.solcast_pv_forecast_forecast_today
      headers:
        - Content-Type: application/json
        - Authorization: Bearer <redacted>
      jq: ".attributes.detailedForecast | map( (.period_start | capture(\"(?<dt>[^+]+)(?<tz>[+-]\\\\d{2}:\\\\d{2})$\")) as $p | {start: .period_start, end: (($p.dt | strptime(\"%Y-%m-%dT%H:%M:%S\") | mktime + 1800 | strftime(\"%Y-%m-%dT%H:%M:%S\")) + $p.tz), value: (.pv_estimate * 1000)}) | tostring"
      timeout: 5s
  - type: custom            # Solcast via HA -- tomorrow (identical jq)
    interval: 15m
    forecast:
      source: http
      uri: https://homeassistant.local/api/states/sensor.solcast_pv_forecast_forecast_tomorrow
      headers:
        - Content-Type: application/json
        - Authorization: Bearer <redacted>
      jq: "<identical to above>"
      timeout: 5s
  - type: template          # small secondary plant
    template: forecast-solar
    lat: 51.1
    lon: 9.4
    dec: 2
    az: 0
    kwp: 4.5
Optional: deterministic demonstration (Go test, no solar setup or midnight wait needed)

Not proposed for the suite as-is (the retention it exercises is intended for price tariffs); it shows how a tomorrow-only source retains the current day:

package tariff

import (
	"testing"
	"time"

	"github.com/evcc-io/evcc/api"
	"github.com/evcc-io/evcc/util"
)

func TestMergeRatesAfterRetainsRollingWindowData(t *testing.T) {
	today := time.Date(2026, 7, 25, 0, 0, 0, 0, time.Local)
	now := today.Add(15 * time.Minute) // shortly after midnight

	data := util.NewMonitor[api.Rates](0)

	// yesterday's fetch: the source covered Jul 25 as "tomorrow"
	stale := api.Rates{
		{Start: today.Add(12 * time.Hour), End: today.Add(12*time.Hour + 30*time.Minute), Value: 22000},
	}
	mergeRatesAfter(data, stale, now.Add(-24*time.Hour))

	// first fetch after midnight: the source now covers Jul 26 only
	fresh := api.Rates{
		{Start: today.Add(36 * time.Hour), End: today.Add(36*time.Hour + 30*time.Minute), Value: 16000},
	}
	mergeRatesAfter(data, fresh, now)

	res, _ := data.Get()
	for _, r := range res {
		if r.Start.Equal(today.Add(12 * time.Hour)) {
			t.Fatalf("rate for the current day retained from yesterday's fetch: %+v", r)
		}
	}
}

mechanism reproduced on current master via the Go test (fails as expected)

/tmp/evcc-master-repro$ go test ./tariff/ -run TestMergeRatesAfterRetainsRollingWindowData -v go: downloading github.com/andig/eebus-go v0.0.0-20260725155950-e735091ff165 go: downloading github.com/andig/spine-go v0.7.1-0.20260725155511-6f83690e6238 go: downloading github.com/evcc-io/ocpp-go v0.0.0-20260727074919-195c10b8758d === RUN TestMergeRatesAfterRetainsRollingWindowData rolling_window_test.go:32: rate for the current day retained from yesterday's fetch: {Start:2026-07-25 12:00:00 +0200 CEST End:2026-07-25 12:30:00 +0200 CEST Value:22000} --- FAIL: TestMergeRatesAfterRetainsRollingWindowData (0.00s) FAIL FAIL github.com/evcc-io/evcc/tariff 0.066s FAIL

Configuration details

See the collapsed "Solar config used (tokens redacted)" block under
"Steps to reproduce". The rest of evcc.yaml (meters, chargers, loadpoints,
grid/feed-in tariffs) is unrelated to this report.

Log details

evcc's own log is clean at any log level -- no error occurs, the doubling is
silent. Raw monitoring captures (15-min cron comparing the HA "today" sensor
peak against the /api/tariff/solar peak) instead:

Bug era (two custom tariffs today/tomorrow):


=== 20260725-0615 ===
HA heute count + peak:   { "count": 48, "peak": 22.1866, "dup_starts": [] }
Tariff peak:             { "peak": 45471.7, "count": 172 }
Ratio tariff/HA:         HA: 22186.6W  Tariff: 45471.7W  Ratio: 2.04


Same day, minutes after switching to a single combined source and restarting:


=== 20260725-0753 ===
HA heute count + peak:   { "count": 48, "peak": 22.1866, "dup_starts": [] }
Tariff peak:             { "peak": 24221.7, "count": 168 }
Ratio tariff/HA:         HA: 22186.6W  Tariff: 24221.7W  Ratio: 1.09

What type of operating system or environment does evcc run on?

Linux

External automation

  • [x] I have made sure that no external automation like HomeAssistant or Node-RED is active or accessing any of the mentioned devices when this issue occurs.

Nightly build

  • [x] I have verified that the issue is reproducible with the latest nightly build

Version

evcc version 0.311.1

1va13n7in avatar Jul 28 '26 06:07 1va13n7in

Investigated and can confirm the root cause described here — this is a genuine bug.

Confirmed mechanism

  • tariff/helper.go mergeRatesAfter retains old rates when End <= newStart && End > now. This "keep the gap between now and the new fetch's start" logic is correct for progressively-extending price tariffs, but breaks for a source whose window rolls forward by a fixed offset (e.g. a "forecast tomorrow" sensor).
  • For a custom forecast source configured under solar: (tariff/tariff.go, run()), periodStart for solar is beginningOfDay() rather than the current slot — this doesn't help, since after midnight the previous day's "tomorrow" fetch (covering what is now today) still has End > beginningOfDay() and End <= newStart (the new fetch's start, which has itself rolled to the next day). So it's retained.
  • tariff/combined.go Rates() groups strictly by Start and sums values (lo.SumBy), so the stale retained day from the "tomorrow" source and the fresh data from the "today" source both land on the same Start timestamps and get summed → doubled current-day values.

I traced through the retention mechanism with the test case from the report (values/dates match, mergeRatesAfter keeps the stale entry), and manually traced tariff.go's run() including the solar-specific beginningOfDay() periodStart — it doesn't prevent the issue.

Native solcast tariff (tariff/solcast.go) is not affected the same way since it always fetches a full rolling multi-day window (hours=96) from a single source, so this specifically hits multiple narrow-window solar sources combined together (e.g. the Solcast-via-HomeAssistant today/tomorrow sensor pair pattern from the report).

Assessment

This looks correctly diagnosed and fixable, but the right fix needs a small design decision rather than being a pure one-liner: mergeRatesAfter's retention semantics are shared across all tariff types (price, forecast, solar, temperature) via tariff/helper.go, and solar forecast tariffs need different semantics (fresh data supersedes rather than fills gaps) without regressing price tariffs or full-window solar sources like native solcast. Leaving this for a maintainer to decide the approach (e.g. option 1 from the report: solar forecast tariffs replace future rates instead of merging) rather than opening a PR on my own judgment call.

🤖 Generated with Claude Code

github-actions[bot] avatar Jul 28 '26 06:07 github-actions[bot]

Matches our findings on the live system, including that the native solcast tariff (single full-window source) is unaffected. Happy to provide a PR with a regression test once a maintainer picks the preferred approach.

1va13n7in avatar Jul 30 '26 04:07 1va13n7in

With missing log/config it's impossible to draw our own conclusions from anaylsis. If you think the fix is clear feel free to open PR.

andig avatar Jul 31 '26 05:07 andig