fix(prediction): key cached provider requests on the settings they read

The file cache keyed provider request methods on their arguments and
code only. They take no arguments besides self and read location,
planes, tokens and past days from the configuration, so after a
configuration change they got the response for the previous one until
the 1-hour TTL expired, also across restarts.

cache_in_file takes an optional key_context, called with the arguments
of each call; a hash of its result is part of the key. Each provider
request declares the settings it is built from with
cache_request("general/latitude", ...), which builds the key context
from them. A change of other settings, e.g. an import value or a tariff
that an adapter pushes on every run, keeps the cache entry. The MD5
digest of the declared values is computed once per settings generation:
ConfigEOS.settings_generation() counts every _setup() (merge, reset,
revert, update) and every set_nested_value().

cache_in_file also takes key_context_hold: after a change of the key
context, a further change within the hold keeps using the valid entry
of the context in use. The first change, a change after the hold and a
forced update apply at once. A result is only stored under the context
it was computed for. cache_request passes its keyword arguments on to
cache_in_file; with_ttl defaults to REQUEST_CACHE_TTL (1 hour) and also
sets key_context_hold, so settings changes cause at most one extra
request per provider and TTL.

In a simulation of 6 hours of 5-minute runs with an import value pushed
on every run and four location and plane edits, the weather and PV
requests run 6 times (as on main), and every edit reaches the provider
within the hour.

Additional changes
Test that every cached request declares the settings it reads, including
those read by helper methods of its module
Test the settings generation counter, the reuse of the digest, the hold
and the cache_request defaults and pass-through
Add general/timezone to BrightSky (in the URL) and Forecast.Solar
(fallback zone of the response)
Clear the hold state with the whole file cache
Add a CHANGELOG entry

Refs: #1559
Signed-off-by: SchaafAlexander <86607129+SchaafAlexander@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
SchaafAlexander
2026-11-20 19:06:40 +01:00
committed by Bobby Noelte
co-authored by Claude Opus 5.5
parent b944d4adfa
commit 3035ec0a4b
24 changed files with 691 additions and 36 deletions
+43
View File
@@ -567,6 +567,49 @@ def test_transient_weather_outage_is_retried(pvforecast_instance):
assert "minutely_15" in data
def test_weather_request_cache_follows_the_configuration(pvforecast_instance, monkeypatch):
"""A configuration change must not get the cached response of the old one (#1559).
Only the settings the request reads count, and settings changes cause at most one
extra request per hour.
"""
sent: list[tuple[int, float]] = []
now = [to_datetime("2026-11-15T12:00:00+00:00")]
monkeypatch.setattr("akkudoktoreos.core.cache._hold_now", lambda: now[0])
monkeypatch.setattr("akkudoktoreos.core.cache._key_context_states", {})
def respond(url, params, timeout):
sent.append((params["past_days"], params["latitude"]))
response = Mock()
response.url = url
response.raise_for_status.return_value = None
response.json.return_value = synthetic_openmeteo()
return response
config = pvforecast_instance.config
with patch(
"akkudoktoreos.prediction.pvforecastakkudoktorlocal.requests.get", side_effect=respond
):
pvforecast_instance._request_local_forecast(force_update=True)
pvforecast_instance._request_local_forecast() # unchanged: from the cache
# A setting the request does not read, e.g. pushed by an adapter on every run.
config.set_nested_value("elecprice/elecpriceimport/import_json", '{"a": [1.0]}')
pvforecast_instance._request_local_forecast()
# Calibration needs the weather of its lookback: more past days.
config.merge_settings_from_dict(
{"pvforecast": {"akkudoktor": {"calibration_enabled": True}}}
)
pvforecast_instance._request_local_forecast()
# A second change within the hour keeps the response until an hour after the first.
now[0] = now[0].add(minutes=10)
config.merge_settings_from_dict({"general": {"latitude": 48.14, "longitude": 11.58}})
pvforecast_instance._request_local_forecast()
now[0] = now[0].add(minutes=51)
pvforecast_instance._request_local_forecast()
assert sent == [(2, LATITUDE), (30, LATITUDE), (30, 48.14)]
@pytest.mark.asyncio
async def test_weather_outage_keeps_the_previous_forecast(pvforecast_instance):
"""One dead weather API must not take the whole prediction update down.