mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-11-25 15:06:20 +01:00
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:
committed by
Bobby Noelte
co-authored by
Claude Opus 5.5
parent
b944d4adfa
commit
3035ec0a4b
@@ -981,6 +981,144 @@ class TestCacheFileDecorators:
|
||||
|
||||
assert received == [{"a": 1, "token": "secret-1"}]
|
||||
|
||||
def test_key_context_is_part_of_the_key(self, cache_file_store):
|
||||
"""State outside the arguments that decides the result gets its own entry (#1559)."""
|
||||
cache_file_store.clear(clear_all=True)
|
||||
|
||||
class Provider:
|
||||
def __init__(self) -> None:
|
||||
self.location = "Berlin"
|
||||
self.calls: list[str] = []
|
||||
|
||||
def context(self, *args, **kwargs):
|
||||
return {"location": self.location}
|
||||
|
||||
@cache_in_file(key_context=lambda self, *args, **kwargs: self.context())
|
||||
def request(self) -> str:
|
||||
self.calls.append(self.location)
|
||||
return f"forecast for {self.location}"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
# Same repr for every configuration, like the prediction providers.
|
||||
return "Provider()"
|
||||
|
||||
provider = Provider()
|
||||
assert provider.request() == "forecast for Berlin"
|
||||
assert provider.request() == "forecast for Berlin"
|
||||
provider.location = "Munich"
|
||||
assert provider.request() == "forecast for Munich"
|
||||
provider.location = "Berlin"
|
||||
assert provider.request() == "forecast for Berlin"
|
||||
|
||||
assert provider.calls == ["Berlin", "Munich"]
|
||||
|
||||
def test_key_context_gets_the_call_arguments(self, cache_file_store):
|
||||
cache_file_store.clear(clear_all=True)
|
||||
seen: list[tuple] = []
|
||||
|
||||
def context(*args, **kwargs):
|
||||
seen.append((args, kwargs))
|
||||
return None
|
||||
|
||||
@cache_in_file(key_context=context)
|
||||
def f(x, y=0):
|
||||
return x + y
|
||||
|
||||
assert f(1, y=2) == 3
|
||||
# Cache control parameters are consumed by the wrapper, not passed on.
|
||||
assert f(1, y=2, force_update=True) == 3 # type: ignore[call-arg]
|
||||
|
||||
assert seen == [((1,), {"y": 2}), ((1,), {"y": 2})]
|
||||
|
||||
@staticmethod
|
||||
def _held_provider():
|
||||
class Provider:
|
||||
def __init__(self) -> None:
|
||||
self.location = "Berlin"
|
||||
self.calls: list[str] = []
|
||||
|
||||
@cache_in_file(
|
||||
with_ttl="2 hours",
|
||||
key_context=lambda self, *args, **kwargs: self.location,
|
||||
key_context_hold="1 hour",
|
||||
)
|
||||
def request(self) -> str:
|
||||
self.calls.append(self.location)
|
||||
return f"forecast for {self.location}"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return "Provider()"
|
||||
|
||||
return Provider()
|
||||
|
||||
@staticmethod
|
||||
def _clock(monkeypatch):
|
||||
now = [to_datetime("2026-11-15T12:00:00+00:00")]
|
||||
monkeypatch.setattr("akkudoktoreos.core.cache._hold_now", lambda: now[0])
|
||||
return now
|
||||
|
||||
def test_key_context_hold_allows_one_change_per_hold(self, cache_file_store, monkeypatch):
|
||||
"""Settings changes lead to at most one extra call per hold duration."""
|
||||
cache_file_store.clear(clear_all=True)
|
||||
now = self._clock(monkeypatch)
|
||||
provider = self._held_provider()
|
||||
|
||||
assert provider.request() == "forecast for Berlin"
|
||||
now[0] = now[0].add(minutes=5)
|
||||
provider.location = "Munich" # first change: applies at once
|
||||
assert provider.request() == "forecast for Munich"
|
||||
now[0] = now[0].add(minutes=5)
|
||||
provider.location = "Hamburg" # within the hold: keeps the Munich result
|
||||
assert provider.request() == "forecast for Munich"
|
||||
now[0] = now[0].add(minutes=30)
|
||||
assert provider.request() == "forecast for Munich"
|
||||
provider.location = "Munich" # back to the settings in use
|
||||
assert provider.request() == "forecast for Munich"
|
||||
provider.location = "Hamburg"
|
||||
now[0] = now[0].add(minutes=26) # 61 minutes after the switch to Munich
|
||||
assert provider.request() == "forecast for Hamburg"
|
||||
|
||||
assert provider.calls == ["Berlin", "Munich", "Hamburg"]
|
||||
|
||||
def test_key_context_hold_yields_to_force_update(self, cache_file_store, monkeypatch):
|
||||
cache_file_store.clear(clear_all=True)
|
||||
now = self._clock(monkeypatch)
|
||||
provider = self._held_provider()
|
||||
|
||||
provider.request()
|
||||
provider.location = "Munich"
|
||||
provider.request()
|
||||
now[0] = now[0].add(minutes=1)
|
||||
provider.location = "Hamburg"
|
||||
assert provider.request(force_update=True) == "forecast for Hamburg"
|
||||
# The forced call stored the Hamburg result under the Hamburg settings.
|
||||
assert provider.request() == "forecast for Hamburg"
|
||||
|
||||
assert provider.calls == ["Berlin", "Munich", "Hamburg"]
|
||||
|
||||
def test_key_context_hold_never_stores_under_other_settings(
|
||||
self, cache_file_store, monkeypatch
|
||||
):
|
||||
"""Without a valid entry to keep, the call is made and keyed on its own settings."""
|
||||
cache_file_store.clear(clear_all=True)
|
||||
now = self._clock(monkeypatch)
|
||||
provider = self._held_provider()
|
||||
|
||||
provider.request()
|
||||
provider.location = "Munich"
|
||||
provider.request()
|
||||
# The entries are gone (e.g. expired); the switch time to Munich is kept.
|
||||
cache_file_store._store.clear()
|
||||
now[0] = now[0].add(minutes=1)
|
||||
provider.location = "Hamburg"
|
||||
assert provider.request() == "forecast for Hamburg"
|
||||
provider.location = "Munich"
|
||||
now[0] = now[0].add(minutes=1)
|
||||
# Hamburg is now in use and has a valid entry: the change back is held.
|
||||
assert provider.request() == "forecast for Hamburg"
|
||||
|
||||
assert provider.calls == ["Berlin", "Munich", "Hamburg"]
|
||||
|
||||
|
||||
class TestFuncCodeHash:
|
||||
def test_hash_is_stable(self):
|
||||
|
||||
@@ -692,6 +692,29 @@ class TestConfigEOS:
|
||||
config_eos_file.reset_settings()
|
||||
assert config_eos_file.optimization.genetic.individuals == 200
|
||||
|
||||
def test_settings_generation_changes_with_every_settings_change(self, config_eos):
|
||||
"""Merge, nested set, failed set, reset and update each start a new generation."""
|
||||
seen = [config_eos.settings_generation()]
|
||||
|
||||
def changed() -> None:
|
||||
generation = config_eos.settings_generation()
|
||||
assert generation not in seen
|
||||
seen.append(generation)
|
||||
|
||||
assert config_eos.settings_generation() == seen[-1]
|
||||
config_eos.merge_settings_from_dict({"prediction": {"hours": 72}})
|
||||
changed()
|
||||
config_eos.set_nested_value("prediction/historic_hours", 72)
|
||||
changed()
|
||||
with pytest.raises(ValueError):
|
||||
config_eos.set_nested_value("prediction/hours", "not a number")
|
||||
changed()
|
||||
config_eos.reset_settings()
|
||||
changed()
|
||||
config_eos.update()
|
||||
changed()
|
||||
assert config_eos.settings_generation() == seen[-1]
|
||||
|
||||
def test_set_nested_value_survives_merge(self, config_eos_file):
|
||||
"""Granular updates are not lost by a later bulk update."""
|
||||
write_config_file(
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import ast
|
||||
import os
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, ClassVar, List, Optional, Union
|
||||
from unittest.mock import patch
|
||||
|
||||
import pandas as pd
|
||||
import pendulum
|
||||
@@ -16,6 +19,8 @@ from akkudoktoreos.prediction.predictionabc import (
|
||||
PredictionProvider,
|
||||
PredictionRecord,
|
||||
PredictionSequence,
|
||||
cache_request,
|
||||
request_config_context,
|
||||
)
|
||||
from akkudoktoreos.utils.datetimeutil import compare_datetimes, to_datetime, to_duration
|
||||
|
||||
@@ -408,3 +413,202 @@ class TestPredictionContainer:
|
||||
async def test_provider_by_id(self, container_with_providers):
|
||||
provider = container_with_providers.provider_by_id("DerivedPredictionProvider")
|
||||
assert isinstance(provider, DerivedPredictionProvider)
|
||||
|
||||
|
||||
class _ConfigHolder:
|
||||
"""Stands in for a provider: the request cache context only reads ``config``."""
|
||||
|
||||
def __init__(self, config) -> None:
|
||||
self.config = config
|
||||
|
||||
|
||||
def test_request_config_context_follows_only_its_settings(config_eos):
|
||||
"""The context changes with the settings a request reads, and only with those."""
|
||||
context = request_config_context("general/latitude", "general/longitude")
|
||||
provider = _ConfigHolder(config_eos)
|
||||
before = context(provider)
|
||||
assert context(provider) == before
|
||||
|
||||
# Other settings, e.g. pushed by an adapter on every run, leave the context alone.
|
||||
config_eos.merge_settings_from_dict({"prediction": {"hours": 72}})
|
||||
config_eos.set_nested_value(
|
||||
"elecprice/elecpriceimport/import_json", '{"elecprice_marketprice_wh": [0.0003]}'
|
||||
)
|
||||
assert context(provider) == before
|
||||
|
||||
config_eos.merge_settings_from_dict({"general": {"latitude": 48.14, "longitude": 11.58}})
|
||||
moved = context(provider)
|
||||
assert moved != before
|
||||
config_eos.set_nested_value("general/latitude", 52.52)
|
||||
assert context(provider) not in (before, moved)
|
||||
|
||||
|
||||
def test_request_config_context_is_a_digest_reused_until_the_settings_change(config_eos):
|
||||
"""The context is a short digest, computed once per settings generation."""
|
||||
import akkudoktoreos.prediction.predictionabc as predictionabc
|
||||
|
||||
context = request_config_context("general/latitude", "pvforecast/planes")
|
||||
provider = _ConfigHolder(config_eos)
|
||||
with patch.object(predictionabc, "json", wraps=predictionabc.json) as json_spy:
|
||||
first = context(provider)
|
||||
for _ in range(3):
|
||||
assert context(provider) == first
|
||||
assert len(first) == 32
|
||||
int(first, 16)
|
||||
assert json_spy.dumps.call_count == 1
|
||||
|
||||
config_eos.merge_settings_from_dict({"general": {"latitude": 48.14}})
|
||||
assert context(provider) != first
|
||||
assert json_spy.dumps.call_count == 2
|
||||
context(provider)
|
||||
assert json_spy.dumps.call_count == 2
|
||||
|
||||
|
||||
def test_request_config_context_needs_a_path():
|
||||
with pytest.raises(ValueError):
|
||||
request_config_context()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"cache_kwargs, expected",
|
||||
[
|
||||
({}, {"with_ttl": "1 hour", "key_context_hold": "1 hour"}),
|
||||
# The TTL also sets the hold: at most one settings-driven request per TTL.
|
||||
({"with_ttl": "3 hours"}, {"with_ttl": "3 hours", "key_context_hold": "3 hours"}),
|
||||
({"with_ttl": None}, {"with_ttl": "1 hour", "key_context_hold": "1 hour"}),
|
||||
(
|
||||
{"with_ttl": "3 hours", "key_context_hold": "30 minutes"},
|
||||
{"with_ttl": "3 hours", "key_context_hold": "30 minutes"},
|
||||
),
|
||||
(
|
||||
{"key_context_hold": None},
|
||||
{"with_ttl": "1 hour", "key_context_hold": None},
|
||||
),
|
||||
# Everything else goes to cache_in_file as is.
|
||||
(
|
||||
{"ignore_params": ["token"], "suffix": ".json", "mode": "w+"},
|
||||
{
|
||||
"with_ttl": "1 hour",
|
||||
"key_context_hold": "1 hour",
|
||||
"ignore_params": ["token"],
|
||||
"suffix": ".json",
|
||||
"mode": "w+",
|
||||
},
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_cache_request_passes_its_options_to_cache_in_file(cache_kwargs, expected):
|
||||
import akkudoktoreos.prediction.predictionabc as predictionabc
|
||||
|
||||
with patch.object(predictionabc, "cache_in_file") as cache_in_file:
|
||||
cache_request("general/latitude", **cache_kwargs)
|
||||
|
||||
kwargs = dict(cache_in_file.call_args.kwargs)
|
||||
key_context = kwargs.pop("key_context")
|
||||
assert key_context.config_paths == ("general/latitude",)
|
||||
assert kwargs == expected
|
||||
|
||||
|
||||
def test_cache_request_builds_the_key_context_itself():
|
||||
with pytest.raises(TypeError):
|
||||
cache_request("general/latitude", key_context=lambda *args, **kwargs: None)
|
||||
|
||||
|
||||
def _cached_requests() -> list[tuple[str, ast.FunctionDef, list[str], dict]]:
|
||||
"""The ``@cache_request`` methods of the prediction package, with their module's methods."""
|
||||
import akkudoktoreos.prediction as prediction_package
|
||||
|
||||
found = []
|
||||
for path in sorted(Path(prediction_package.__file__).parent.glob("*.py")):
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"))
|
||||
methods = {n.name: n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)}
|
||||
for method in methods.values():
|
||||
for decorator in method.decorator_list:
|
||||
if isinstance(decorator, ast.Call) and getattr(decorator.func, "id", "") == (
|
||||
"cache_request"
|
||||
):
|
||||
paths = [arg.value for arg in decorator.args] # type: ignore[attr-defined]
|
||||
found.append((path.name, method, paths, methods))
|
||||
return found
|
||||
|
||||
|
||||
# Inherited properties that read the configuration.
|
||||
_INHERITED_CONFIG_READS = {
|
||||
"end_datetime": "prediction/hours",
|
||||
"keep_datetime": "prediction/historic_hours",
|
||||
}
|
||||
|
||||
|
||||
def _config_reads(method: ast.FunctionDef, methods: dict, seen: set) -> set[str]:
|
||||
"""Configuration paths a method reads, following ``self.<method>`` of its module.
|
||||
|
||||
The time stamp of the response (``self.update_datetime = ...``) is not part of the
|
||||
request and left out.
|
||||
"""
|
||||
|
||||
def walk(node):
|
||||
if isinstance(node, ast.Assign) and any(
|
||||
isinstance(target, ast.Attribute) and target.attr == "update_datetime"
|
||||
for target in node.targets
|
||||
):
|
||||
return
|
||||
yield node
|
||||
for child in ast.iter_child_nodes(node):
|
||||
yield from walk(child)
|
||||
|
||||
reads: set[str] = set()
|
||||
for node in walk(method):
|
||||
if not isinstance(node, ast.Attribute):
|
||||
continue
|
||||
if isinstance(node.value, ast.Name) and node.value.id == "self":
|
||||
if node.attr in _INHERITED_CONFIG_READS:
|
||||
reads.add(_INHERITED_CONFIG_READS[node.attr])
|
||||
if node.attr in methods and node.attr not in seen:
|
||||
seen.add(node.attr)
|
||||
reads |= _config_reads(methods[node.attr], methods, seen)
|
||||
parts = []
|
||||
inner: ast.expr = node
|
||||
while isinstance(inner, ast.Attribute):
|
||||
parts.append(inner.attr)
|
||||
inner = inner.value
|
||||
if isinstance(inner, ast.Name) and inner.id == "self" and parts[-1] == "config":
|
||||
if len(parts) > 1:
|
||||
reads.add("/".join(reversed(parts[:-1])))
|
||||
return {read for read in reads if not any(other.startswith(read + "/") for other in reads)}
|
||||
|
||||
|
||||
def test_provider_requests_are_cached_with_cache_request():
|
||||
"""Provider requests use ``cache_request``, which keys on their settings (#1559)."""
|
||||
import akkudoktoreos.prediction as prediction_package
|
||||
|
||||
package = Path(prediction_package.__file__).parent
|
||||
plain = [
|
||||
path.name
|
||||
for path in sorted(package.glob("*.py"))
|
||||
if "@cache_in_file(" in path.read_text(encoding="utf-8")
|
||||
]
|
||||
assert plain == []
|
||||
assert len(_cached_requests()) >= 16
|
||||
|
||||
|
||||
def test_cached_requests_declare_every_setting_they_read(config_eos):
|
||||
"""A setting the request reads but the key leaves out gives stale responses (#1559).
|
||||
|
||||
A declared setting the request does not read costs extra requests.
|
||||
"""
|
||||
problems = []
|
||||
for module, method, paths, methods in _cached_requests():
|
||||
for path in paths:
|
||||
config_eos.get_nested_value(path) # raises for an unknown setting
|
||||
reads = _config_reads(method, methods, {method.name})
|
||||
missing = sorted(
|
||||
read for read in reads if not any(read == p or read.startswith(p + "/") for p in paths)
|
||||
)
|
||||
unused = sorted(
|
||||
p
|
||||
for p in paths
|
||||
if not any(read == p or read.startswith(p + "/") or p.startswith(read + "/") for read in reads)
|
||||
)
|
||||
if missing or unused:
|
||||
problems.append((module, method.name, missing, unused))
|
||||
assert problems == []
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user