diff --git a/CHANGELOG.md b/CHANGELOG.md index 526cf27f..f38be6ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -227,6 +227,11 @@ test procedure. These changes are not yet a tagged release. - Database: records persist and reload, compaction runs, `delete_by_datetime(None, None)` wipes all data, and NaN values are dropped when reading series. - The file cache (`cache_in_file`) keys stay the same across restarts, so the cache keeps hitting. +- Cached provider requests (weather, PV forecast, electricity price, feed-in tariff) follow the + settings they are built from: after a change of e.g. the location, the PV planes, a token or the + past days of the local PV forecast, the next update requests new data instead of reusing the + response for the previous settings for up to an hour. Other settings changes don't cause + requests, and settings changes cause at most one extra request per provider and hour. - Parallel GENETIC evaluation workers stop reliably at the end of a run; fitness-cache memory is released after each run. - Home Assistant adapter: config entities with the state `0` or `off` are applied, unknown diff --git a/src/akkudoktoreos/config/config.py b/src/akkudoktoreos/config/config.py index be6b1be9..281af248 100644 --- a/src/akkudoktoreos/config/config.py +++ b/src/akkudoktoreos/config/config.py @@ -470,6 +470,8 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults): _config_autosave: ClassVar[str] = "" # Settings provided at runtime, e.g. by the REST interface. Highest priority after CLI. _runtime_settings: ClassVar[dict[str, Any]] = {} + # Counts the setups and nested value changes, see `settings_generation()`. + _settings_generation: ClassVar[int] = 0 # A ClassVar: without the annotation pydantic makes it a private attribute, # and the class attribute would be a (truthy) descriptor object. _force_documentation_mode: ClassVar[bool] = False @@ -813,6 +815,7 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults): def _setup(self, *args: Any, **kwargs: Any) -> None: """Re-initialize global settings.""" logger.debug("Config setup with parameters {} {}", args, kwargs) + ConfigEOS._settings_generation += 1 # Assure settings base knows the singleton EOS configuration SettingsBaseModel.config = self @@ -849,6 +852,20 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults): for message in warnings: logger.warning(message) + @classmethod + def settings_generation(cls) -> int: + """Number that changes whenever the settings may have changed. + + It counts every setup of the settings (merge, reset, revert, update) and every + `set_nested_value()`. Use it to keep values derived from the settings until the + next change. A direct attribute assignment, e.g. ``config.general.latitude = 1.0``, + does not count. + + Returns: + The current generation. + """ + return cls._settings_generation + def merge_settings(self, settings: SettingsEOS) -> None: """Merges the provided settings into the global settings for EOS, with optional overwrite. @@ -906,7 +923,11 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults): path (str): A '/'-separated path to the nested attribute (e.g. "server/port"). value (Any): The new value to set. """ - super().set_nested_value(path, value) + try: + super().set_nested_value(path, value) + finally: + # Also after a partly applied change. + ConfigEOS._settings_generation += 1 # Remember as runtime setting to survive re-evaluation of the configuration sources. # List indices can not be expressed by the settings dictionary - remember the whole list. diff --git a/src/akkudoktoreos/core/cache.py b/src/akkudoktoreos/core/cache.py index dcaa0a6a..5e960c52 100644 --- a/src/akkudoktoreos/core/cache.py +++ b/src/akkudoktoreos/core/cache.py @@ -5,6 +5,7 @@ both in memory (using an LRU cache) and in temporary files. It also includes mechanisms for managing cache file expiration and retrieval. """ +import contextlib import functools import hashlib import inspect @@ -816,6 +817,11 @@ class CacheFileStore(ConfigMixin, SingletonMixin): Raises: OSError: If there's an error during file deletion. """ + if clear_all: + # Without entries there is nothing to hold (see `key_context_hold`). + # Suppressed: clear_all also runs on __del__, possibly at interpreter exit. + with contextlib.suppress(Exception), _key_context_lock: + _key_context_states.clear() # Some weired logic to prevent calling to_datetime on clear_all. # Clear_all may be set on __del__. At this time some info for to_datetime will # not be available anymore. @@ -963,6 +969,17 @@ class CacheFileStore(ConfigMixin, SingletonMixin): return store_loaded +# `cache_in_file(key_context_hold=...)` state per argument key: +# (context hash in use, when it was switched to, last held context hash). +_key_context_states: dict[str, tuple[str, Optional[DateTime], Optional[str]]] = {} +_key_context_lock = threading.Lock() + + +def _hold_now() -> DateTime: + """Current time for `cache_in_file(key_context_hold=...)`; tests replace it.""" + return to_datetime() + + def cache_in_file( ignore_params: List[str] = [], force_update: Optional[bool] = None, @@ -972,6 +989,8 @@ def cache_in_file( mode: Literal["w", "w+", "wb", "wb+", "r", "r+", "rb", "rb+"] = "wb+", delete: bool = False, suffix: Optional[str] = None, + key_context: Optional[Callable[..., Any]] = None, + key_context_hold: Optional[Any] = None, ) -> Callable[[Callable[Param, RetType]], Callable[Param, RetType]]: """Cache the output of a function into a temporary file. @@ -1011,6 +1030,19 @@ def cache_in_file( suffix (Optional[str], optional): A file suffix (e.g., ".txt" or ".json") for the cache file. Defaults to None. If not provided, files are pickled by default. + key_context (Optional[Callable[..., Any]], optional): + Called with the arguments of each call; a hash of the ``repr()`` of its result is + part of the cache key. Use it when the result depends on state the arguments do + not carry, e.g. a method that builds its request from the configuration of + ``self``. Defaults to None. + key_context_hold (Union[timedelta, str, int, float, None], optional): + Limits how often a change of the `key_context` leads to a new call. After the + context of a call changed, a later change within this duration keeps using the + still valid cache entry of the current context instead of calling the function. + The first change, and any change once the duration passed, applies at once. + A forced update applies the change at once. Without a valid entry to keep, the + function is called for the new context. Defaults to None (every change applies + at once). Returns: Callable[[Callable[Param, RetType]], Callable[Param, RetType]]: @@ -1029,8 +1061,10 @@ def cache_in_file( Notes: - The cache key is based on the function arguments after excluding those in - `ignore_params`, and on a hash of the function's code, defaults and captured - values (see `_get_func_code_hash`). + `ignore_params`, on a hash of the function's code, defaults and captured + values (see `_get_func_code_hash`), and on the `key_context`, if given. + - With `key_context_hold`, a cached result is only ever stored under the context it + was computed for; holding only reuses an existing entry. - The control parameters (`force_update`, `until_date`, `until_datetime`, `with_ttl`) are consumed by the wrapper and are not forwarded to the wrapped function. @@ -1044,6 +1078,55 @@ def cache_in_file( func_code_hash = _get_func_code_hash(func) # Follows functools.wraps wrappers to the signature of the wrapped function. func_signature = inspect.signature(func) + hold = None if key_context_hold is None else to_duration(key_context_hold) + + def held_context(base_key: str, context_hash: str, call_force_update: bool) -> str: + """Return the context hash to try for this call, see `key_context_hold`. + + The context in use is kept while its hold lasts; the caller falls back to + `switch_context` if it has no valid cache entry. + """ + with _key_context_lock: + state = _key_context_states.get(base_key) + if state is None: + if len(_key_context_states) >= 256: + _key_context_states.clear() + _key_context_states[base_key] = (context_hash, None, None) + return context_hash + active, switched_at, held = state + if context_hash == active: + if held is not None: + _key_context_states[base_key] = (active, switched_at, None) + return active + if ( + not call_force_update + and hold is not None + and switched_at is not None + and _hold_now() < switched_at + hold + ): + return active + _key_context_states[base_key] = (context_hash, _hold_now(), None) + return context_hash + + def switch_context(base_key: str, context_hash: str) -> None: + """Use `context_hash` from now on; its hold starts now.""" + with _key_context_lock: + _key_context_states[base_key] = (context_hash, _hold_now(), None) + + def report_held(base_key: str, context_hash: str) -> None: + """Log once per change that a changed context waits for the hold to end.""" + with _key_context_lock: + state = _key_context_states.get(base_key) + if state is None or state[2] == context_hash or state[1] is None: + return + _key_context_states[base_key] = (state[0], state[1], context_hash) + until = state[1] + hold # type: ignore[operator] + logger.info( + "{}: changed settings apply from {} on; the cached result of the previous " + "settings is used until then.", + func.__qualname__, + to_datetime(until, as_string=True), + ) def wrapper(*args: Param.args, **kwargs: Param.kwargs) -> RetType: # Control parameters given at call time apply to this call only. @@ -1073,6 +1156,17 @@ def cache_in_file( # Create key based on argument names, argument values, and function code key = str(_cache_key_arguments(func_signature, args, kwargs, ignore_params)) key += func_code_hash + base_key = key + context_hash = use_hash = "" + if key_context is not None: + # State outside the arguments that decides the result, e.g. the + # configuration a provider builds its request from. + context = repr(key_context(*args, **kwargs)) + context_hash = hashlib.sha256(context.encode("utf-8")).hexdigest() + use_hash = context_hash + if hold is not None: + use_hash = held_context(base_key, context_hash, bool(call_force_update)) + key = base_key + use_hash result: Optional[RetType | bytes] = None # Get cache file that is currently valid @@ -1082,6 +1176,20 @@ def cache_in_file( until_datetime=expiry["until_datetime"], ttl_duration=expiry["with_ttl"], ) + if use_hash != context_hash: + if cache_file is None: + # Nothing to keep: call for the current context, never store the + # result under another one. + switch_context(base_key, context_hash) + key = base_key + context_hash + cache_file = CacheFileStore().get( + key, + until_date=expiry["until_date"], + until_datetime=expiry["until_datetime"], + ttl_duration=expiry["with_ttl"], + ) + else: + report_held(base_key, context_hash) if not call_force_update and cache_file is not None: # cache file is available try: @@ -1095,6 +1203,10 @@ def cache_in_file( logger.info(f"Read failed: {e}") # Fail gracefully - recreate the cache file in this call call_force_update = True + if use_hash != context_hash: + # Recreate it for the current context, not the held one. + switch_context(base_key, context_hash) + key = base_key + context_hash if call_force_update or cache_file is None: # Otherwise, call the function and save its result to the cache. # Call first: a call that raises leaves no empty cache file behind. diff --git a/src/akkudoktoreos/prediction/elecpriceakkudoktor.py b/src/akkudoktoreos/prediction/elecpriceakkudoktor.py index 1ed06c08..ce4effc8 100644 --- a/src/akkudoktoreos/prediction/elecpriceakkudoktor.py +++ b/src/akkudoktoreos/prediction/elecpriceakkudoktor.py @@ -14,9 +14,9 @@ from loguru import logger from pydantic import ValidationError from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.cache import cache_in_file from akkudoktoreos.core.pydantic import PydanticBaseModel from akkudoktoreos.prediction.elecpriceabc import ElecPriceProvider +from akkudoktoreos.prediction.predictionabc import cache_request from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime, to_duration @@ -90,7 +90,7 @@ class ElecPriceAkkudoktor(ElecPriceProvider): raise ValueError(error_msg) return akkudoktor_data - @cache_in_file(with_ttl="1 hour") + @cache_request("general/timezone", "prediction/hours") def _request_forecast(self) -> AkkudoktorElecPrice: """Fetch electricity price forecast data from Akkudoktor API. diff --git a/src/akkudoktoreos/prediction/elecpriceenergycharts.py b/src/akkudoktoreos/prediction/elecpriceenergycharts.py index 392b132c..2c8ff83a 100644 --- a/src/akkudoktoreos/prediction/elecpriceenergycharts.py +++ b/src/akkudoktoreos/prediction/elecpriceenergycharts.py @@ -16,9 +16,9 @@ from loguru import logger from pydantic import Field, ValidationError from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.cache import cache_in_file from akkudoktoreos.core.pydantic import PydanticBaseModel from akkudoktoreos.prediction.elecpriceabc import ElecPriceProvider +from akkudoktoreos.prediction.predictionabc import cache_request from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime, to_duration @@ -171,7 +171,7 @@ class ElecPriceEnergyCharts(ElecPriceProvider): return bidding_zone.value return str(bidding_zone) - @cache_in_file(with_ttl="1 hour") + @cache_request("elecprice/energycharts", "prediction/hours") def _request_forecast(self, start_date: Optional[str] = None) -> EnergyChartsElecPrice: """Fetch electricity price forecast data from Energy-Charts API. diff --git a/src/akkudoktoreos/prediction/elecpricesmard.py b/src/akkudoktoreos/prediction/elecpricesmard.py index cab98d81..51ee7fc6 100644 --- a/src/akkudoktoreos/prediction/elecpricesmard.py +++ b/src/akkudoktoreos/prediction/elecpricesmard.py @@ -9,12 +9,12 @@ from loguru import logger from pydantic import Field, ValidationError from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.cache import cache_in_file from akkudoktoreos.core.pydantic import PydanticBaseModel from akkudoktoreos.prediction.elecpriceenergycharts import ( ElecPriceEnergyCharts, EnergyChartsElecPrice, ) +from akkudoktoreos.prediction.predictionabc import cache_request from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration SMARD_BASE_URL = "https://www.smard.de/app/chart_data" @@ -130,7 +130,7 @@ class ElecPriceSMARD(ElecPriceEnergyCharts): selected.append(chunk_start) return selected - @cache_in_file(with_ttl="1 hour") + @cache_request("elecprice/smard", "general/timezone", "prediction/hours") def _request_forecast(self, start_date: Optional[str] = None) -> EnergyChartsElecPrice: """Fetch and normalize quarter-hourly German/Luxembourg day-ahead prices from SMARD.""" if not self.ems_start_datetime: diff --git a/src/akkudoktoreos/prediction/elecpricetibber.py b/src/akkudoktoreos/prediction/elecpricetibber.py index 9acf871c..6e2d1506 100644 --- a/src/akkudoktoreos/prediction/elecpricetibber.py +++ b/src/akkudoktoreos/prediction/elecpricetibber.py @@ -9,9 +9,9 @@ from loguru import logger from pydantic import Field, ValidationError from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.cache import cache_in_file from akkudoktoreos.core.pydantic import PydanticBaseModel from akkudoktoreos.prediction.elecpriceabc import ElecPriceProvider +from akkudoktoreos.prediction.predictionabc import cache_request from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration TIBBER_GRAPHQL_URL = "https://api.tibber.com/v1-beta/gql" @@ -217,7 +217,7 @@ class ElecPriceTibber(ElecPriceProvider): tomorrow_count = len(subscription.priceInfo.tomorrow) return history_count, today_count, tomorrow_count - @cache_in_file(with_ttl="1 hour") + @cache_request("elecprice/tibber/access_token") def _request_forecast(self) -> TibberGraphQLResponse: """Fetch electricity price data from the Tibber GraphQL API.""" access_token = self.config.elecprice.tibber.access_token diff --git a/src/akkudoktoreos/prediction/feedintariffakkudoktor.py b/src/akkudoktoreos/prediction/feedintariffakkudoktor.py index f72134c7..b3aeee1a 100644 --- a/src/akkudoktoreos/prediction/feedintariffakkudoktor.py +++ b/src/akkudoktoreos/prediction/feedintariffakkudoktor.py @@ -10,12 +10,12 @@ import requests from loguru import logger from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.cache import cache_in_file from akkudoktoreos.prediction.elecpriceakkudoktor import ( AkkudoktorElecPrice, ElecPriceAkkudoktor, ) from akkudoktoreos.prediction.feedintariffabc import FeedInTariffProvider +from akkudoktoreos.prediction.predictionabc import cache_request from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration @@ -51,7 +51,7 @@ class FeedInTariffAkkudoktor(FeedInTariffProvider): """Return the unique provider identifier.""" return "FeedInTariffAkkudoktor" - @cache_in_file(with_ttl="1 hour") + @cache_request("general/timezone", "prediction/hours") def _request_forecast(self) -> AkkudoktorElecPrice: """Fetch market prices from the public Akkudoktor API.""" if not self.ems_start_datetime: diff --git a/src/akkudoktoreos/prediction/feedintariffdvhubonline.py b/src/akkudoktoreos/prediction/feedintariffdvhubonline.py index 5a844f4d..dc274dc6 100644 --- a/src/akkudoktoreos/prediction/feedintariffdvhubonline.py +++ b/src/akkudoktoreos/prediction/feedintariffdvhubonline.py @@ -10,8 +10,8 @@ from loguru import logger from pydantic import Field from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.cache import cache_in_file from akkudoktoreos.prediction.feedintariffabc import FeedInTariffProvider +from akkudoktoreos.prediction.predictionabc import cache_request from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration @@ -63,7 +63,7 @@ class FeedInTariffDvhubOnline(FeedInTariffProvider): return FeedInTariffDvhubOnlineCommonSettings() return settings - @cache_in_file(with_ttl="1 hour") + @cache_request("feedintariff/dvhubonline") def _request_forecast(self, start_date: str, end_date: str) -> dict[str, Any]: """Fetch market prices from the dvhub.online price API.""" settings = self._provider_settings() diff --git a/src/akkudoktoreos/prediction/feedintariffenergycharts.py b/src/akkudoktoreos/prediction/feedintariffenergycharts.py index ab7ae002..7ed2ec99 100644 --- a/src/akkudoktoreos/prediction/feedintariffenergycharts.py +++ b/src/akkudoktoreos/prediction/feedintariffenergycharts.py @@ -10,13 +10,13 @@ from loguru import logger from pydantic import Field from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.cache import cache_in_file from akkudoktoreos.prediction.elecpriceenergycharts import ( ElecPriceEnergyCharts, EnergyChartsBiddingZones, EnergyChartsElecPrice, ) from akkudoktoreos.prediction.feedintariffabc import FeedInTariffProvider +from akkudoktoreos.prediction.predictionabc import cache_request from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration @@ -108,7 +108,7 @@ class FeedInTariffEnergyCharts(FeedInTariffProvider): return bidding_zone.value return str(bidding_zone) - @cache_in_file(with_ttl="1 hour") + @cache_request("feedintariff/energycharts", "prediction/hours") def _request_forecast(self, start_date: Optional[str] = None) -> EnergyChartsElecPrice: """Fetch electricity price forecast data from Energy-Charts API. diff --git a/src/akkudoktoreos/prediction/feedintarifftibber.py b/src/akkudoktoreos/prediction/feedintarifftibber.py index e6afca32..620f72fb 100644 --- a/src/akkudoktoreos/prediction/feedintarifftibber.py +++ b/src/akkudoktoreos/prediction/feedintarifftibber.py @@ -9,7 +9,6 @@ import requests from loguru import logger from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.cache import cache_in_file from akkudoktoreos.prediction.elecpricetibber import ( TIBBER_GRAPHQL_URL, TIBBER_PRICE_QUERY_QUARTER_HOURLY, @@ -18,6 +17,7 @@ from akkudoktoreos.prediction.elecpricetibber import ( TibberPricePoint, ) from akkudoktoreos.prediction.feedintariffabc import FeedInTariffProvider +from akkudoktoreos.prediction.predictionabc import cache_request from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration @@ -47,7 +47,7 @@ class FeedInTariffTibber(FeedInTariffProvider): """Keep enough history for seasonal price extrapolation.""" return 24 * 35 - @cache_in_file(with_ttl="1 hour") + @cache_request("elecprice/tibber/access_token") def _request_forecast(self) -> TibberGraphQLResponse: """Request strictly quarter-hourly Tibber prices. diff --git a/src/akkudoktoreos/prediction/predictionabc.py b/src/akkudoktoreos/prediction/predictionabc.py index a2738805..25c20237 100644 --- a/src/akkudoktoreos/prediction/predictionabc.py +++ b/src/akkudoktoreos/prediction/predictionabc.py @@ -8,11 +8,15 @@ This module is designed for use in predictive modeling workflows, facilitating t and manipulation of configuration and prediction data in a clear, scalable, and structured manner. """ -from typing import Generic, List, Optional, TypeVar +import hashlib +import json +from typing import Any, Callable, Generic, List, Optional, TypeVar from loguru import logger from pydantic import Field, computed_field +from pydantic_core import to_jsonable_python +from akkudoktoreos.core.cache import Param, RetType, cache_in_file from akkudoktoreos.core.coreabc import MeasurementMixin from akkudoktoreos.core.dataabc import ( DataABC, @@ -25,6 +29,94 @@ from akkudoktoreos.core.dataabc import ( ) from akkudoktoreos.utils.datetimeutil import DateTime, Duration, to_duration +# Default for how long a provider response stays cached, and the shortest time between +# two requests caused by settings changes (see `cache_request`). +REQUEST_CACHE_TTL = "1 hour" + + +def request_config_context(*config_paths: str) -> Callable[..., str]: + """Build a cache key context from the settings a provider request is built from. + + The returned function takes the provider (``self`` of the cached method) and returns + the MD5 digest of the values at ``config_paths`` (``'/'``-separated, as for + ``get_nested_value``). The digest is kept until the settings change + (``ConfigEOS.settings_generation()``). + + Args: + *config_paths: The settings the request reads, e.g. ``"general/latitude"``. + + Returns: + The key context function for ``cache_in_file(key_context=...)``. + """ + if not config_paths: + raise ValueError("A request cache context needs at least one configuration path.") + paths = tuple(config_paths) + # (config id, settings generation, digest) of the last result. + last: list[Optional[tuple[int, int, str]]] = [None] + + def context(provider: Any, *args: Any, **kwargs: Any) -> str: + config = provider.config + generation = config.settings_generation() + cached = last[0] + if cached is not None and cached[0] == id(config) and cached[1] == generation: + return cached[2] + values = {path: to_jsonable_python(config.get_nested_value(path)) for path in paths} + text = json.dumps(values, sort_keys=True, default=str) + digest = hashlib.md5(text.encode("utf-8"), usedforsecurity=False).hexdigest() + last[0] = (id(config), generation, digest) + return digest + + context.config_paths = paths # type: ignore[attr-defined] + return context + + +def cache_request( + *config_paths: str, + **cache_kwargs: Any, +) -> Callable[[Callable[Param, RetType]], Callable[Param, RetType]]: + """Cache a provider request in a file, keyed on the settings it is built from (#1559). + + Provider request methods read their parameters (location, planes, tokens, past days) + from the configuration, not from their arguments. The values at ``config_paths`` are + part of the cache key, so a change of them requests new data instead of reusing the + response for the previous settings. Other settings changes leave the cache alone. + + To protect the provider rate limits, settings changes lead to at most one extra request + per ``with_ttl``: a further change within that time keeps the cached response until + then (``cache_in_file(key_context_hold=...)``). A forced update applies it at once. + + Example: + .. code-block:: python + + @cache_request("general/latitude", "general/longitude") + def _request_forecast(self) -> dict: ... + + # A provider with a stricter rate limit: cache and hold for 3 hours. + @cache_request("pvforecast/planes", with_ttl="3 hours") + def _request_forecast(self) -> dict: ... + + Args: + *config_paths: Every setting the request reads, as ``'/'``-separated paths. + They build the ``key_context``. + **cache_kwargs: Passed on to ``cache_in_file``. ``with_ttl`` defaults to + ``REQUEST_CACHE_TTL``, and ``key_context_hold`` defaults to ``with_ttl``. + + Returns: + The ``cache_in_file`` decorator. + """ + if "key_context" in cache_kwargs: + raise TypeError("cache_request builds the key_context from the config_paths.") + with_ttl = cache_kwargs.pop("with_ttl", None) + if with_ttl is None: + with_ttl = REQUEST_CACHE_TTL + key_context_hold = cache_kwargs.pop("key_context_hold", with_ttl) + return cache_in_file( + with_ttl=with_ttl, + key_context=request_config_context(*config_paths), + key_context_hold=key_context_hold, + **cache_kwargs, + ) + class PredictionABC(DataABC, MeasurementMixin): """Base class for handling prediction data. diff --git a/src/akkudoktoreos/prediction/pvforecastakkudoktor.py b/src/akkudoktoreos/prediction/pvforecastakkudoktor.py index 94b40b2c..05e8316b 100644 --- a/src/akkudoktoreos/prediction/pvforecastakkudoktor.py +++ b/src/akkudoktoreos/prediction/pvforecastakkudoktor.py @@ -84,8 +84,8 @@ import requests from loguru import logger from pydantic import Field, ValidationError, computed_field, field_validator -from akkudoktoreos.core.cache import cache_in_file from akkudoktoreos.core.pydantic import PydanticBaseModel +from akkudoktoreos.prediction.predictionabc import cache_request from akkudoktoreos.prediction.pvforecast import PVForecastPlaneSetting from akkudoktoreos.prediction.pvforecastabc import PVForecastDataRecord from akkudoktoreos.prediction.pvforecastakkudoktorlocal import PVForecastAkkudoktorLocal @@ -317,7 +317,7 @@ class PVForecastAkkudoktor(PVForecastAkkudoktorLocal[PVForecastAkkudoktorDataRec return url - @cache_in_file(with_ttl="1 hour") + @cache_request("general/latitude", "general/longitude", "general/timezone", "pvforecast/planes") def _request_forecast(self) -> AkkudoktorForecast: """Fetch PV forecast data from Akkudoktor API. diff --git a/src/akkudoktoreos/prediction/pvforecastakkudoktorlocal.py b/src/akkudoktoreos/prediction/pvforecastakkudoktorlocal.py index cb86112d..65dac44d 100644 --- a/src/akkudoktoreos/prediction/pvforecastakkudoktorlocal.py +++ b/src/akkudoktoreos/prediction/pvforecastakkudoktorlocal.py @@ -44,8 +44,8 @@ from loguru import logger from pydantic import Field, PrivateAttr, field_validator, model_validator from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.cache import cache_in_file from akkudoktoreos.measurement.measurement import MeterPeriod +from akkudoktoreos.prediction.predictionabc import cache_request from akkudoktoreos.prediction.pvforecastabc import ( PVForecastDataRecordT, PVForecastProvider, @@ -626,7 +626,13 @@ class PVForecastAkkudoktorLocal(PVForecastProvider[PVForecastDataRecordT]): return forecast_days, min(MAX_PAST_DAYS, past_days) - @cache_in_file(with_ttl="1 hour") + @cache_request( + "general/latitude", + "general/longitude", + "prediction/hours", + "prediction/historic_hours", + "pvforecast/akkudoktor", + ) def _request_local_forecast(self) -> Any: """Fetch raw irradiance and weather from Open-Meteo.""" latitude = self.config.general.latitude diff --git a/src/akkudoktoreos/prediction/pvforecastforecastsolar.py b/src/akkudoktoreos/prediction/pvforecastforecastsolar.py index 3c558425..5fb0092a 100644 --- a/src/akkudoktoreos/prediction/pvforecastforecastsolar.py +++ b/src/akkudoktoreos/prediction/pvforecastforecastsolar.py @@ -29,7 +29,7 @@ from loguru import logger from pydantic import Field from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.cache import cache_in_file +from akkudoktoreos.prediction.predictionabc import cache_request from akkudoktoreos.prediction.pvforecastabc import PVForecastProvider from akkudoktoreos.utils.datetimeutil import DateTime, to_datetime @@ -157,7 +157,13 @@ class PVForecastForecastSolar(PVForecastProvider): base = f"{base}/{api_key}" return f"{base}/estimate/{latitude}/{longitude}/{float(tilt)}/{fs_az}/{float(peakpower)}" - @cache_in_file(with_ttl="1 hour") + @cache_request( + "general/latitude", + "general/longitude", + "general/timezone", + "pvforecast/planes", + "pvforecast/forecastsolar", + ) def _request_forecast(self) -> dict: """Fetch and aggregate the Forecast.Solar estimate across all configured planes.""" planes = self.config.pvforecast.planes or [] diff --git a/src/akkudoktoreos/prediction/pvforecastpvnode.py b/src/akkudoktoreos/prediction/pvforecastpvnode.py index 80140618..7c08f4e3 100644 --- a/src/akkudoktoreos/prediction/pvforecastpvnode.py +++ b/src/akkudoktoreos/prediction/pvforecastpvnode.py @@ -30,7 +30,7 @@ from loguru import logger from pydantic import Field from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.cache import cache_in_file +from akkudoktoreos.prediction.predictionabc import cache_request from akkudoktoreos.prediction.pvforecastabc import PVForecastProvider from akkudoktoreos.utils.datetimeutil import to_datetime @@ -154,7 +154,12 @@ class PVForecastPVNode(PVForecastProvider): rows.append((date, round(power, 1))) return rows - @cache_in_file(with_ttl="1 hour") + @cache_request( + "general/latitude", + "general/longitude", + "pvforecast/planes", + "pvforecast/pvnode", + ) def _request_forecast(self) -> Any: """Fetch the PV forecast from pvnode.com (saved site or inline planes).""" settings = self._settings diff --git a/src/akkudoktoreos/prediction/pvforecastsolcast.py b/src/akkudoktoreos/prediction/pvforecastsolcast.py index 3436ea56..515d087b 100644 --- a/src/akkudoktoreos/prediction/pvforecastsolcast.py +++ b/src/akkudoktoreos/prediction/pvforecastsolcast.py @@ -25,7 +25,7 @@ from loguru import logger from pydantic import Field from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.cache import cache_in_file +from akkudoktoreos.prediction.predictionabc import cache_request from akkudoktoreos.prediction.pvforecastabc import PVForecastProvider from akkudoktoreos.utils.datetimeutil import to_datetime @@ -78,7 +78,7 @@ class PVForecastSolcast(PVForecastProvider): minutes = int(match.group(2) or 0) return hours * 60 + minutes - @cache_in_file(with_ttl="1 hour") + @cache_request("pvforecast/solcast") def _request_forecast(self) -> Any: """Fetch the rooftop-site forecast from Solcast.""" settings = self._settings diff --git a/src/akkudoktoreos/prediction/weatherbrightsky.py b/src/akkudoktoreos/prediction/weatherbrightsky.py index 8cbe834e..36ff8c13 100644 --- a/src/akkudoktoreos/prediction/weatherbrightsky.py +++ b/src/akkudoktoreos/prediction/weatherbrightsky.py @@ -14,7 +14,7 @@ import pandas as pd import requests from loguru import logger -from akkudoktoreos.core.cache import cache_in_file +from akkudoktoreos.prediction.predictionabc import cache_request from akkudoktoreos.prediction.weatherabc import WeatherDataRecord, WeatherProvider from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration @@ -78,7 +78,7 @@ class WeatherBrightSky(WeatherProvider): """Return the unique identifier for the BrightSky provider.""" return "BrightSky" - @cache_in_file(with_ttl="1 hour") + @cache_request("general/latitude", "general/longitude", "general/timezone", "prediction/hours") def _request_forecast(self) -> dict: """Fetch weather forecast data from BrightSky API. diff --git a/src/akkudoktoreos/prediction/weatherclearoutside.py b/src/akkudoktoreos/prediction/weatherclearoutside.py index a71c34ba..f6e3f462 100644 --- a/src/akkudoktoreos/prediction/weatherclearoutside.py +++ b/src/akkudoktoreos/prediction/weatherclearoutside.py @@ -19,7 +19,7 @@ import pandas as pd import requests from loguru import logger -from akkudoktoreos.core.cache import cache_in_file +from akkudoktoreos.prediction.predictionabc import cache_request from akkudoktoreos.prediction.weatherabc import WeatherDataRecord, WeatherProvider from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration, to_timezone @@ -79,7 +79,7 @@ class WeatherClearOutside(WeatherProvider): def provider_id(cls) -> str: return "ClearOutside" - @cache_in_file(with_ttl="1 hour") + @cache_request("general/latitude", "general/longitude") def _request_forecast(self) -> requests.Response: """Requests weather forecast from ClearOutside. diff --git a/src/akkudoktoreos/prediction/weatheropenmeteo.py b/src/akkudoktoreos/prediction/weatheropenmeteo.py index 341defc1..5c33441c 100644 --- a/src/akkudoktoreos/prediction/weatheropenmeteo.py +++ b/src/akkudoktoreos/prediction/weatheropenmeteo.py @@ -13,7 +13,7 @@ import pandas as pd import requests from loguru import logger -from akkudoktoreos.core.cache import cache_in_file +from akkudoktoreos.prediction.predictionabc import cache_request from akkudoktoreos.prediction.weatherabc import WeatherDataRecord, WeatherProvider from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration @@ -109,7 +109,7 @@ class WeatherOpenMeteo(WeatherProvider): """Return the unique identifier for the Open-Meteo provider.""" return "OpenMeteo" - @cache_in_file(with_ttl="1 hour") + @cache_request("general/latitude", "general/longitude", "general/timezone", "prediction/hours") def _request_forecast(self) -> dict: """Fetch weather forecast data from Open-Meteo API. diff --git a/tests/test_cache.py b/tests/test_cache.py index 97864e0b..2a3c76cc 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -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): diff --git a/tests/test_config.py b/tests/test_config.py index 501bc68c..fdab8673 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -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( diff --git a/tests/test_predictionabc.py b/tests/test_predictionabc.py index 6f339e85..64815519 100644 --- a/tests/test_predictionabc.py +++ b/tests/test_predictionabc.py @@ -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.`` 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 == [] diff --git a/tests/test_pvforecastakkudoktorlocal.py b/tests/test_pvforecastakkudoktorlocal.py index 46fb84d6..c4657368 100644 --- a/tests/test_pvforecastakkudoktorlocal.py +++ b/tests/test_pvforecastakkudoktorlocal.py @@ -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.