Skip to content

Tariffs: einheitlicher Abrufplan für alle Anbieter - #4405

Open
seaspotter wants to merge 8 commits into
openWB:masterfrom
seaspotter:tariff-update-window
Open

seaspotter wants to merge 8 commits into
openWB:masterfrom
seaspotter:tariff-update-window

Conversation

@seaspotter

@seaspotter seaspotter commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

related UI: openWB/openwb-ui-settings#1185

Die Abrufplanung der Strompreise war uneinheitlich und hat Anbieter unnötig oft abgefragt. Dieser PR ist unabhängig von #4332 und kann einzeln gemergt werden. Rebase wer zuletzt gemerged wird.

Abrufplan (für alle Anbieter gleich)

  • Erster Abruf 5-30 Minuten vor 14 Uhr (zufällig), danach stündlich, bis die Preise für den Folgetag da sind. Nach Mitternacht endet die Wiederholung.
  • Fehlt der Folgetag ab 19 Uhr noch, gibt es eine Warnung, der Abruf läuft weiter.
  • Ein Abruf wird nur übernommen, wenn er neuere Preise liefert. Spätestens beim Ablauf der bekannten Preise wird neu abgefragt. Nach einer Exception weiter nach 5 Minuten.

Warum die Zeiten vereinheitlicht wurden
Bisher hatte jeder Anbieter eigene update_hours (z. B. Ostrom 2/8/14/20, EKZ 18/19, Rabot und Westfalen Wind 0) und ohne neue Preise wurde alle 5 Minuten wiederholt (bei Octopus je 3 API-Aufrufe). Die Anbieter veröffentlichen zwischen ca. 14 und 18 Uhr (Rabot 16 Uhr, smartENERGY 17 Uhr laut deren Dokumentation). Der stündliche Abruf ab 14 Uhr erfasst sie alle innerhalb einer Stunde, braucht deutlich weniger Anfragen und ist für alle gleich. update_hours ist entfernt (mit Migration). Ausnahme: Westfalen Wind liefert die Preise des laufenden Tages ab 0 Uhr, dafür gibt es ein festes Merkmal im Code, damit die Warnung nicht jeden Abend erscheint. Westfalen Wind, hat aber leider null Dokumentation, Annahme: Hier könnte man auch früher abrufen, aber ich finde dazu keine Info.

Dauerhafte Fehler
Falsche Zugangsdaten werden nicht mehr ständig neu versucht. Das Modul zeigt einen Fehler und fragt erst nach einer Änderung der Konfiguration wieder ab: HTTP 401/403 bei allen Anbietern, Octopus (Anmeldung), Tibber (Token), Naturstrom (Refresh Token), EWS und Westfalen Wind (fehlende Zugangsdaten).

Weitere Korrekturen

  • Groupe E: API v1 ist abgeschaltet (HTTP 410), der Tarif lieferte keine Preise mehr. Umgestellt auf v2, Zeitfenster in UTC statt fest +01:00.
  • aWATTar: ohne Zeitraum liefert die API nur 24 Stunden, jetzt ab der aktuellen Stunde für 2 Tage, damit der Folgetag vollständig ist.
  • Westfalen Wind: Token-URL mit abschließendem Slash, sonst leitet der Server per HTTP um (Passwort im Klartext).

Summary by Sourcery

Unify electricity tariff polling across providers and prevent repeated requests for missing next-day prices or unrecoverable authentication failures.

Bug Fixes:

  • Switch Groupe E tariff retrieval to the v2 API and use UTC time windows, restoring price retrieval after the v1 API shutdown.
  • Request a two-day price horizon from aWATTar so the following day is covered, and extend the forecast coverage through the end of tomorrow for Octopus.
  • Use the trailing-slash Westfalen Wind token URL to avoid an HTTP redirect that could expose credentials.

Enhancements:

  • Apply one shared tariff polling schedule across providers: randomized first request shortly before 14:00, hourly retries while next-day prices are missing, and polling no later than the end of known prices.
  • Stop polling after permanent authentication or credential errors until configuration changes, while retaining short retries for transient errors.
  • Keep existing prices when a provider returns no newer data, and schedule the next request only after updated prices have been stored.

Tests:

  • Add coverage for the shared scheduling policy, permanent errors, provider forecast windows, API changes, and datastore migration.

Chores:

  • Bump the datastore version and migrate tariff provider configurations by removing the obsolete update_hours setting while preserving other configuration values.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 8 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="packages/modules/electricity_pricing/flexible_tariffs/octopusenergy/tariff.py" line_range="82-83" />
<code_context>
-        data = self._graphql_request(mutation, variables)
+        try:
+            data = self._graphql_request(mutation, variables)
+        except OctopusEnergyGraphQlError as e:
+            raise PermanentTariffError(f"Anmeldung bei Octopus fehlgeschlagen, bitte E-Mail und Passwort prüfen: {e}")

         if "obtainKrakenToken" not in data or data["obtainKrakenToken"] is None:
</code_context>
<issue_to_address>
**Temporary errors park tariff updates**

When octopus returns a temporary GraphQL error during authentication, `_graphql_request` raises `OctopusEnergyGraphQlError` for GraphQL errors, and `authenticate` converts every such error into `PermanentTariffError`. The common updater then parks requests for a year, leaving prices stale.

Distinguish temporary GraphQL service errors from permanent credential errors so temporary errors use the normal retry backoff.

Also at `packages/modules/electricity_pricing/flexible_tariffs/octopusenergy/tariff.py:84`.
</issue_to_address>

### Comment 2
<location path="packages/modules/common/configurable_tariff.py" line_range="76" />
<code_context>
+                        self.fault_state.error(f"{self.fault_state.fault_str} - Es wird erst nach einer Änderung der "
+                                               "Konfiguration erneut abgefragt.")
+                        self.fault_state.store_error()
+                        self._set_next_query_time(int(timecheck.create_timestamp()) + PERMANENT_ERROR_PARK_SECONDS)
+                    else:
+                        self._delay_next_query()
</code_context>
<issue_to_address>
**Corrected credentials stay parked**

When a permanent authentication error is followed by a provider configuration change, the rebuilt tariff module reuses `get.next_query_time`, which still holds the year-long park timestamp, so `update()` skips requests with the corrected credentials until that timestamp expires.

Reset or reschedule the shared `get.next_query_time` when the provider configuration changes.
</issue_to_address>

### Comment 3
<location path="packages/modules/common/configurable_tariff.py" line_range="111" />
<code_context>
+        if prices_end <= now:
+            # Kein Preis für den aktuellen Zeitpunkt: bei Anbietern, die um 0 Uhr die Preise des Tages liefern, ist das
+            # kurz nach Mitternacht normal, sonst eine Störung des Anbieters, die nicht minütlich abgefragt werden muss
+            self._delay_next_query(RETRY_BACKOFF_SECONDS if not self.publishes_day_ahead else RETRY_INTERVAL_SECONDS)
+            return
+        if not self.publishes_day_ahead:
</code_context>
<issue_to_address>
**Expired prices trigger overnight polling**

When a day-ahead provider's known prices expire before its next prices are available, `_schedule_next_query` schedules another hourly query for expired prices, so the provider is polled through the night or morning instead of waiting for the next day's first try.

Schedule the next first try for a day-ahead provider when its known prices have expired and newer prices are unavailable.

Also at `packages/modules/common/configurable_tariff.py:112`.
</issue_to_address>

### Comment 4
<location path="packages/modules/common/configurable_tariff.py" line_range="118" />
<code_context>
+        else:
+            tomorrow = now + timedelta(days=1)
+            tomorrow_start = tomorrow.replace(hour=0, minute=0, second=0, microsecond=0)
+            if latest_start >= tomorrow_start:
+                next_query = self._first_try(tomorrow)
+            else:
</code_context>
<issue_to_address>
**Partial forecasts delay missing prices**

When a provider returns some prices for tomorrow but its response does not cover the full day, `_schedule_next_query` treats `latest_start >= tomorrow_start` as proof that tomorrow's prices are available, so it waits until the next first try and leaves later tomorrow slots unavailable.

Do not treat the presence of a tomorrow timestamp as proof that the full day's prices are available; continue querying while tomorrow's prices are incomplete.
</issue_to_address>

### Comment 5
<location path="packages/modules/common/configurable_tariff.py" line_range="134-138" />
<code_context>
-            # neu abgefragt, bis es welche gibt (siehe #3703)
-            self._delay_next_query()
+        latest_price_timestamp = max((int(ts) for ts in tariff_state.prices.keys()), default=0)
+        if latest_price_timestamp <= last_known_timestamp:
+            # Keine neueren Preise, z.B. weil die Preise für den Folgetag noch nicht veröffentlicht sind: die
+            # bekannten Preise behalten (siehe #3703)
+            tariff_state = TariffState(prices=dict(self.get.prices))
+        self._schedule_next_query(tariff_state.prices, self.__calculate_price_timeslot_length(tariff_state))
         return tariff_state

</code_context>
<issue_to_address>
**Older response overwrites newer prices**

When a tariff request runs longer than the loadvars join timeout and a later cycle starts another update before the first finishes, both `update()` calls can pass the due-time check before either publishes its next query time. If the newer response finishes first, the slower response still compares against its earlier `last_known_timestamp` snapshot, accepts its now-stale prices, and replaces the newer prices users see.

Serialize tariff updates or re-check the current stored maximum timestamp immediately before accepting and publishing a response.
</issue_to_address>

### Comment 6
<location path="packages/modules/common/configurable_tariff.py" line_range="104" />
<code_context>
                         self.__finalize_update_status(timeslot_length_seconds, tariff_state)
                 except Exception as e:
                     log.exception(f"Fehler beim Aktualisieren der Tarifdaten {e}")
-                    self._delay_next_query()
+                    if self._is_permanent_error(e):
+                        self.fault_state.error(f"{self.fault_state.fault_str} - Es wird erst nach einer Änderung der "
</code_context>
<issue_to_address>
**Empty responses cause frequent polling**

When a provider successfully returns an empty price list, `_schedule_next_query` calls `_delay_next_query()` with its five-minute default, so empty responses are retried every five minutes instead of following the hourly polling schedule.

Schedule the hourly retry for a successful response with no prices instead of using the default five-minute delay.
</issue_to_address>

### Comment 7
<location path="packages/modules/common/configurable_tariff.py" line_range="127" />
<code_context>
+                next_query = first_try if now < first_try else now + timedelta(seconds=RETRY_INTERVAL_SECONDS)
+        # spätestens, wenn die bekannten Preise ablaufen
+        next_query = min(next_query, prices_end)
+        self._set_next_query_time(int(next_query.timestamp()))
+        log.debug(f"Nächster Abruf der {self.tariff_type} Strompreise geplant für: {next_query}")

</code_context>
<issue_to_address>
**Schedule persists before prices**

When the process stops after the next-query-time publish but before the fetched prices are stored, `_schedule_next_query()` publishes the next query time before `__store_and_publish_updated_data()` persists the fetched prices. A process exit between those writes leaves the old prices paired with a schedule derived from the new response, potentially deferring the next fetch until the following day while users still have stale data.

Persist the accepted prices before publishing the schedule, or make restart recovery invalidate the schedule when it is newer than the stored prices.
</issue_to_address>

### Comment 8
<location path="packages/modules/electricity_pricing/flexible_tariffs/groupe_e/tariff_test.py" line_range="50-51" />
<code_context>
+    tariff.fetch_prices(GroupeETariffConfiguration())
+
+    query = requests_mock.last_request.qs
+    assert query["start_timestamp"] == ["2026-07-01t12:00:00z"]
+    assert query["end_timestamp"] == ["2026-07-03t12:00:00z"]
</code_context>
<issue_to_address>
**Correct UTC window fails test**

When the request window is formatted as the uppercase ISO strings in `readApi`, `test_request_window_is_in_utc_and_starts_with_the_current_hour` expects lowercase `t` and `z`, but the query values retain the uppercase `T` and `Z` produced by `strftime`; the assertions fail for the correct request.

Use uppercase `T` and `Z` in both expected query values.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

@LKuemmel LKuemmel added this to the 2.5.0 milestone Nov 27, 2026
@LKuemmel
LKuemmel self-requested a review November 30, 2026 10:42
@seaspotter

Copy link
Copy Markdown
Collaborator Author

@sourcery-ai review

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 6 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="packages/modules/common/configurable_tariff.py" line_range="131" />
<code_context>
+        # nach dem Abruf lesen: dauert er lange, kann ein anderer Abruf inzwischen neuere Preise gespeichert haben
+        last_known_timestamp = max((int(ts) for ts in self.get.prices.keys()), default=0)
+        latest_price_timestamp = max((int(ts) for ts in tariff_state.prices.keys()), default=0)
+        if latest_price_timestamp <= last_known_timestamp:
+            # Keine neueren Preise, z.B. weil die Preise für den Folgetag noch nicht veröffentlicht sind: die
+            # bekannten Preise behalten (siehe #3703)
</code_context>
<issue_to_address>
**Older prices overwrite newer results**

When two updates for the same tariff overlap, both read the same stored prices, and the older response commits last, the timestamp comparison and store are not atomic, so the older response passes the comparison and replaces the newer prices and next-query time; callers see stale tariff data and scheduling.

Serialize the comparison and store so an older response cannot commit after a newer one.

Also at `packages/modules/common/configurable_tariff.py:68`.
</issue_to_address>

### Comment 2
<location path="packages/modules/common/configurable_tariff.py" line_range="131-134" />
<code_context>
+        # nach dem Abruf lesen: dauert er lange, kann ein anderer Abruf inzwischen neuere Preise gespeichert haben
+        last_known_timestamp = max((int(ts) for ts in self.get.prices.keys()), default=0)
+        latest_price_timestamp = max((int(ts) for ts in tariff_state.prices.keys()), default=0)
+        if latest_price_timestamp <= last_known_timestamp:
+            # Keine neueren Preise, z.B. weil die Preise für den Folgetag noch nicht veröffentlicht sind: die
+            # bekannten Preise behalten (siehe #3703)
+            tariff_state = TariffState(prices=dict(self.get.prices))
         return tariff_state

</code_context>
<issue_to_address>
**Partial responses discard valid prices**

When a provider returns at least one newer price but omits other still-valid prices already stored, `latest_price_timestamp` can be newer even when the response omits still-valid slots from `self.get.prices`; `__call_component_updater` then replaces the stored price map with that partial response, so callers lose prices they already had.

Merge newer response prices with still-valid stored prices, or verify response completeness before replacing the stored map.
</issue_to_address>

### Comment 3
<location path="packages/modules/common/configurable_tariff.py" line_range="76" />
<code_context>
+                        self.fault_state.error(f"{self.fault_state.fault_str} - Es wird erst nach einer Änderung der "
+                                               "Konfiguration erneut abgefragt.")
+                        self.fault_state.store_error()
+                        self._set_next_query_time(int(timecheck.create_timestamp()) + PERMANENT_ERROR_PARK_SECONDS)
+                    else:
+                        self._delay_next_query()
</code_context>
<issue_to_address>
**Fixed credentials remain parked**

When credentials are changed while the service is stopped after a permanent error, then the service restarts, a provider configured with valid credentials after a restart retains the persisted `next_query_time` from the previous permanent-error park. `update()` then skips fetching until that timestamp expires, so prices remain stale despite the configuration change.

Associate the parked state with the configuration that caused it, and clear it when startup loads a different configuration, including when no prior module exists.
</issue_to_address>

### Comment 4
<location path="packages/modules/common/configurable_tariff.py" line_range="31" />
<code_context>
-LATE_WARNING_OFFSET_HOURS: int = 2
+# Nach einem dauerhaften Fehler (z.B. falsche Zugangsdaten) wird erst nach einer Änderung der Konfiguration
+# wieder abgefragt
+PERMANENT_ERROR_PARK_SECONDS: int = 365 * 24 * ONE_HOUR_SECONDS

 log = logging.getLogger(__name__)
</code_context>
<issue_to_address>
**Permanent errors retry after a year**

When a permanent error remains unresolved for a year, `PERMANENT_ERROR_PARK_SECONDS` schedules another update after 365 days, so `update()` retries the unchanged configuration and logs another failure instead of waiting for a configuration change.

Park permanent errors until the configuration changes, with no timed retry.

Also at `packages/modules/common/configurable_tariff.py:76`.
</issue_to_address>

### Comment 5
<location path="packages/modules/common/configurable_tariff.py" line_range="164" />
<code_context>
         now = datetime.now()
-        warning_hour = min(self.tariff_update_hours) + LATE_WARNING_OFFSET_HOURS
-        if now.hour < warning_hour:
+        if now.hour < TOMORROW_WARNING_HOUR:
             return False
         # Datum vor dem Nullsetzen der Uhrzeit erhöhen - +24h in Sekunden träfe an Tagen mit Zeitumstellung
</code_context>
<issue_to_address>
**Westfalen Wind gets nightly warnings**

When westfalen Wind has not published tomorrow's prices by 19:00, `__is_tomorrow_price_missing_after_late_hour` applies the missing-tomorrow check to Westfalen Wind, so it reports a warning for the provider's expected publication schedule and users see a recurring false warning.

Exclude Westfalen Wind from the missing-tomorrow warning until its expected publication time.
</issue_to_address>

### Comment 6
<location path="packages/modules/electricity_pricing/flexible_tariffs/groupe_e/tariff_test.py" line_range="50" />
<code_context>
+    tariff.fetch_prices(GroupeETariffConfiguration())
+
+    query = requests_mock.last_request.qs
+    assert query["start_timestamp"] == ["2026-07-01t12:00:00z"]
+    assert query["end_timestamp"] == ["2026-07-03t12:00:00z"]
</code_context>
<issue_to_address>
**Correct UTC requests fail assertions**

When the request query contains the uppercase `T` and `Z` emitted by the timestamp formatters, the `test_request_window_is_in_utc_and_starts_with_the_current_hour` assertion at line 50 and `test_fetch_prices_requests_two_days` assertions at lines 32–33 expect lowercase `t` and `z`; the formatted timestamps preserve uppercase `T` and `Z` in the decoded query, so these tests fail for correctly formatted requests.

Expect uppercase `T` and `Z` in both tests' decoded query values.

Also at `packages/modules/electricity_pricing/flexible_tariffs/ostrom/tariff_test.py:32-33`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants