Repository navigation
Tariffs: einheitlicher Abrufplan für alle Anbieter - #4405
Open
seaspotter wants to merge 8 commits into
Open
seaspotter wants to merge 8 commits into
seaspotter wants to merge 8 commits into
Conversation
… stop on permanent errors
There was a problem hiding this comment.
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>
LKuemmel
self-requested a review
November 30, 2026 10:42
LKuemmel
reviewed
Dec 1, 2026
Collaborator
Author
|
@sourcery-ai review |
There was a problem hiding this comment.
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>
LKuemmel
approved these changes
Dec 2, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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)
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_hoursist 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
Summary by Sourcery
Unify electricity tariff polling across providers and prevent repeated requests for missing next-day prices or unrecoverable authentication failures.
Bug Fixes:
Enhancements:
Tests:
Chores: