diff --git a/AGENTS.md b/AGENTS.md index 0c48ba42..ac7a4ffd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -51,6 +51,7 @@ Detailed rules live in `ai/skills/`. Load the relevant skill for the task: | `ai/skills/commit-messages/SKILL.md` | Creating/checking commit messages | | `ai/skills/energy-domain/SKILL.md` | Optimization, adapters, units/signs | | `ai/skills/filename-conventions/SKILL.md` | Creating/renaming files | +| `ai/skills/optimizer-architecture/SKILL.md` | Optimizers, their parameter preparation, simulation, solution conversion | | `ai/skills/python-environment/SKILL.md` | Before running uv, make, pytest, mypy, ruff or any Python | | `ai/skills/python-quality/SKILL.md` | Writing/modifying Python | | `ai/skills/rest-api/SKILL.md` | Adding/changing REST endpoints, API error responses | diff --git a/GLOSSARY.md b/GLOSSARY.md index a4b49d85..5507bc3d 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -6,10 +6,64 @@ user-facing docs use another name, it is listed under _Avoid_. ## Optimization +**Optimizer**: +One optimization algorithm (such as GENETIC or GENETIC0) together with its parameter preparation, +simulation, simulation devices and solution conversion. +_Avoid_: optimization algorithm (for the whole), optimization + +**Parameter preparation**: +The part of an optimizer that derives its optimization parameters from configuration, predictions, +measurements, the run start and the warm start, once before each optimization run; the only part of +an optimizer that reads configuration, predictions or measurements. +_Avoid_: parameter creation, request building + +**Solution conversion**: +The part of an optimizer that turns the outcome of an optimization run into the optimization +solution and the energy management plan. +_Avoid_: solution post-processing + +**Optimization request**: +The input a client sends to start an optimization run through the API; parameter preparation +completes it into optimization parameters. +_Avoid_: optimization parameters (for client input) + +**Optimization result**: +The output of an optimizer's run, specific to that optimizer, before solution conversion. +_Avoid_: solution (for this) + +**Optimization solution**: +The optimizer-independent outcome of an optimization run that the energy management publishes, +together with the energy management plan. +_Avoid_: result (for this) + +**Warm start**: +The result of an optimizer's previous optimization run, used to seed its next run. +_Avoid_: start solution, previous solution + **Optimization parameters**: The complete, valid input set handed to one optimizer for one optimization run. _Avoid_: optimization input, request parameters +**Simulation device**: +An optimizer's own model of a device (battery, inverter, home appliance, ...) that its simulation +steps through an optimization run, built only from the optimization parameters. +_Avoid_: device (for this), device settings + +**EMS state**: +What the energy management keeps between optimization runs, such as the run start, the last +results and the run cache; it reaches an optimizer only as arguments of parameter preparation. +_Avoid_: EMS data + +**Golden input**: +A stored optimizer input whose expected output (optimization solution or optimization result) is +kept with it, so a test can show that a refactoring does not change results. +_Avoid_: test fixture (for this), reference data + +**Replay file**: +A golden input made of complete optimization parameters plus the expected optimization result, so +an optimization run can be repeated without configuration, predictions or measurements. +_Avoid_: snapshot, recording + **Fallback value**: A default or heuristic value that replaces an invalid or missing input while the optimization parameters are prepared, always reported as an error. diff --git a/ai/skills/energy-domain/SKILL.md b/ai/skills/energy-domain/SKILL.md index 2193dddf..4c4f7f7a 100644 --- a/ai/skills/energy-domain/SKILL.md +++ b/ai/skills/energy-domain/SKILL.md @@ -7,6 +7,9 @@ description: Use when working on optimization logic, adapters, controllers, devi - Keep optimization logic separate from device-specific communication where practical. +- How an optimizer is structured, what it may read and import, and how it + stays independent of other optimizers: see the `optimizer-architecture` + skill. - Follow existing adapter and controller interfaces. - Respect the distinction between long-horizon energy optimization and fast local device control. diff --git a/ai/skills/optimizer-architecture/SKILL.md b/ai/skills/optimizer-architecture/SKILL.md new file mode 100644 index 00000000..7e419865 --- /dev/null +++ b/ai/skills/optimizer-architecture/SKILL.md @@ -0,0 +1,197 @@ +--- +name: optimizer-architecture +description: Use when creating, changing, refactoring or removing an optimizer (GENETIC, GENETIC0 or a new one), its parameter preparation, simulation, simulation devices, solution conversion, or the code that runs optimizers. +--- + +# Optimizer Architecture + +Terms as in `GLOSSARY.md`: **optimizer**, **parameter preparation**, **optimization +parameters**, **solution conversion**, **warm start**. The decisions and their reasons are in +`docs/adr/` 0003 to 0011; read the ADR before deviating from a rule here, and flag any conflict. + +## One optimizer, four parts + +| Part | May use | +|---|---| +| Parameter preparation (`prepare.py` or `prepare/`) | configuration, predictions, measurements, and the run start and warm start passed in as arguments | +| Algorithm (`run()`) | the optimization parameters only | +| Simulation and simulation devices | the optimization parameters only | +| Solution conversion (`convert()`) | the optimization parameters and the result of the run only | + +- **Hard rule:** outside parameter preparation, an optimizer never reads + configuration, predictions, measurements or EMS state, directly or through a + helper that does (e.g. `configured_grid_interpolator_backend()`, the EMS run + cache in `core.cache`). This includes data only needed to present the + solution: time zone, device IDs, run start and the prediction series the run + used travel in the optimization parameters. The modules and names this + covers are listed once, in `WORLD_MODULES`, `WORLD_NAMES` and `EMS_*` of + `tests/test_optimizerarchitecture.py`; that list is authoritative. Among + them: `config`, `prediction`, `measurement`, `adapter`, `server`, + `core.ems`, `core.cache`, the `core.*settings` and database modules, the + `core.coreabc` mixins and getters, `OptimizationBase` and the shared device + configuration (`devices.settings`, `devices.profile`, `devices.devices`, + `devices.devicesabc`). From `optimization.optimization` only the contract + class `OptimizationSolution` may be imported (`CONTRACT_NAMES`). +- Parameter preparation runs once per run, never fails, never returns `None` and follows the + "Optimization parameters are always valid" rules of the `energy-domain` skill. +- Parameter preparation does not read EMS state either (`core.ems`, + `get_ems()`, `EnergyManagementSystemMixin`, `StartMixin`); the energy + management passes the run start and the warm start as arguments. No part of + an optimizer, its preparation included, imports `akkudoktoreos.server`. +- Only `optimizer.py`, the package `__init__.py` and the parameter + preparation itself import the parameter preparation. Any other module would + reach the configuration through it. The package and `optimizer.py` + may re-export the preparation, so the other modules import neither; only + the package imports `optimizer.py`. + +## The interface + +This is the one maintained copy of the interface; ADR 0006 records the decision and links here. + +```python +class Optimizer(Protocol[P, Q, R]): + name: str + async def prepare(self, start_datetime: DateTime, warm_start: R | None) -> P + async def prepare_from_request( + self, request: Q, start_datetime: DateTime, warm_start: R | None + ) -> P + def run(self, parameters: P) -> R + def convert(self, parameters: P, result: R) -> tuple[OptimizationSolution, EnergyManagementPlan] +``` + +- `run()` is deterministic: the same optimization parameters give the same result. Generations, + individuals, seed and penalties are part of the optimization parameters; apply a REST override + (e.g. `?ngen=`) to the parameters before `run()`, never beside them. +- **Optimization parameters (`P`), including the simulation's device + parameters, are plain dataclasses, never Pydantic models** (ADR 0009). They + are valid because parameter preparation builds them valid, not because a + model validates them. Optimization requests (`Q`) and settings models are + Pydantic models: validation and public schemas belong where external input + arrives. +- **Optimization requests never go straight into `run()`.** A REST endpoint + passes the client's optimization request (`Q`) to the optimizer's + `prepare_from_request()`, which + completes it from the configuration with the same fallback rules as + `prepare()`. Keep the request's public schema unchanged; add fields the run + needs to the optimization parameters, not to the request. +- A run must be reproducible from its stored optimization parameters alone. Add a test that runs + from a stored parameter file when you change what goes into the parameters. + +## Layout and names (ADR 0010) + +Everything of an optimizer lives in `src/akkudoktoreos/optimization//`, +`` being the optimizer's name in lowercase (`genetic`, `genetic0`); its +simulation devices in `devices/` below it. Modules are `.py`, +classes ``. This table is the one maintained copy; ADR 0010 links here. + +| Role | Module | Class | Kind | +|---|---|---|---| +| settings | `settings.py` | `Settings` | Pydantic, `optimization.` | +| request | `request.py` | `Request` | Pydantic, public API | +| parameters | `parameters.py` | `Parameters` | dataclass, input of `run()` | +| preparation | `prepare.py` | `prepare()`, `prepare_from_request()` | | +| optimizer | `optimizer.py` | `Optimizer` | implements the interface | +| algorithm | `algorithm.py` | | the search | +| result | `result.py` | `Result` | dataclass, output of `run()` | +| simulation | `simulation.py`, `devices/.py` | ``, `Parameters` | dataclass parameters | +| conversion | `convert.py` | `convert()` | | +| visualization | `visualize.py` | | renders parameters and result | +| API | `api.py` | REST router | fed by FastAPI dependencies | + +- A new module that fits no role still gets the `` prefix. Do not + invent a second name for an existing role. +- Dataclasses are `@dataclass(frozen=True, slots=True)`. A run never changes + its inputs. +- Only `settings.py`, `request.py`, parameter preparation and + `api.py` may import `pydantic` or `akkudoktoreos.core.pydantic`. + +## Independence + +- An optimizer never imports another optimizer. +- **Duplicate code instead of sharing it.** Simulation physics (efficiency curves, AC/DC energy + solvers, device models) is copied into each optimizer that needs it. Never move simulation code + into a shared module, and never merge copies across optimizers to remove duplication. A fix in + one copy reaches another optimizer only through a deliberate change to that optimizer. +- An optimizer may import: generic utilities (such as `datetimeutil`; Pydantic only in the roles allowed above), the + output contract (`OptimizationSolution`, the energy management plan) and, in parameter + preparation only, the configuration settings, including the shared operation-mode enums and + settings-side resolution such as battery profiles. Translate those into the optimizer's own + types during parameter preparation; do not pass settings objects or enums from the + configuration into the simulation. +- Code outside an optimizer imports nothing from it but its package + (`optimization//__init__.py`), which exports what the registry and the + settings field need. Converting device + settings into an optimizer's device parameters belongs to that optimizer's parameter + preparation, not to `devices/settings/`: the shared device configuration + (`devices.settings`, `devices.profile`, `devices.devices`, `devices.devicesabc`) + never imports an optimizer, not even its package. + +## What an optimizer owns + +Its package holds everything specific to it: the settings model `optimization.` and the +validation of its horizons, parameter preparation, run, simulation, simulation devices, solution +conversion, visualization, its REST endpoints (contributed as a router) and its EOSdash wizard +steps. The energy management, the server and EOSdash use only the registry and the interface; +never add a branch per optimizer there. + +None of these gets an exception from the hard rule (ADR 0011): + +- `visualize.py` renders from the optimization parameters and result + only, like `convert()`. +- `api.py` fetches nothing itself. It declares placeholder dependency + functions for the last parameters and result and the run trigger; the + generic server fills them in through `app.dependency_overrides` from the + registry. It imports FastAPI, Pydantic and its request, never + configuration, EMS state or `akkudoktoreos.server`. +- Wizard steps are field metadata in `settings.py` that EOSdash reads; + no EOSdash code inside an optimizer. + +Removing an optimizer touches exactly four places in the production code: its directory, its +registry entry, its static settings field in `OptimizationCommonSettings`, and a configuration +migration step that drops `optimization.` and switches `optimization.algorithm` to a +remaining optimizer. If a change makes removal need anything else, it breaks this rule. What +belongs only to the optimizer goes with it: its tests, its test data and, while the architecture +test's `BASELINE` lists violations of the optimizer, those entries. The remaining optimizers' +tests pass unchanged. + +## Enforcement + +`tests/test_optimizerarchitecture.py` (ADR 0007) checks the import rules above +against `BASELINE`, the violations that existed when it was introduced. + +- Parameter preparation is recognised by file name: + `optimization//prepare.py` or a subpackage + `optimization//prepare/` (a package; a plain `prepare.py` does not + count). Only there may an optimizer import the modules and names of the hard + rule, except EMS state and the server. +- When you find another module or helper that reads configuration, + predictions, measurements or EMS state, add it to the list in the test. + That is the only case in which `BASELINE` may grow: by the existing uses the + new list entry reveals, in the same commit, and named in the pull request. +- `optimization//settings.py` may import `config.configabc` to define + `optimization.`, nothing else from the configuration. +- Otherwise never add an entry to `BASELINE`, and never rename a module to + `*prepare.py` or `*settings.py` just to pass the test. Remove the entries + your change fixes; the test fails on stale entries. +- The test discovers optimizers (every package under `optimization/`); do not + hard-code optimizer names in it. +- It cannot detect simulation physics moved into a new shared module, nor a + helper that reads the configuration but is missing from the list. Both are + enforced by review: treat them as hard violations. +- A failing architecture test is a hard violation. + +## Refactoring versus behaviour change (ADR 0008) + +- **Refactoring an optimizer never changes its results.** With a fixed seed, + every golden input (`tests/testdata//optimize_result_*.json`, + replay files) gives the same solution as before. Never regenerate or edit + golden data in a refactoring; if a golden test fails, the refactoring is + wrong. +- A change that alters results is a behaviour change: its own pull request, + declared as such, never mixed with refactoring. +- **GENETIC0 is frozen.** No bug fixes, no behaviour changes, no tuning. Only + structural changes needed to follow this architecture, each proven + result-identical by its golden tests. Fix a GENETIC0 bug in GENETIC instead, + and report it to the user. +- Before refactoring an optimizer, add replay files: complete optimization + parameters in the new parameter type plus the expected result. diff --git a/docs/adr/0003-optimizers-see-only-their-optimization-parameters.md b/docs/adr/0003-optimizers-see-only-their-optimization-parameters.md new file mode 100644 index 00000000..dae68893 --- /dev/null +++ b/docs/adr/0003-optimizers-see-only-their-optimization-parameters.md @@ -0,0 +1,26 @@ +# Optimizers see only their optimization parameters + +Configuration, predictions, measurements and EMS state change while an optimization run is in +progress, and an optimizer that reads them live can optimize against one state and report the plan +against another. So the parameter preparation of an optimizer is the only part of it that reads +configuration, predictions or measurements (EMS state reaches it only as arguments, see +[0006](0006-optimizer-interface-prepare-run-convert.md)); it runs once before the optimization run and +puts everything the run needs into the optimization parameters. The algorithm, the simulation, the +simulation devices and the solution conversion use nothing but the optimization parameters and the +results of the run, never configuration, predictions, measurements or EMS state, neither directly +nor through a helper that reads them (the complete list of modules and names is kept in the +architecture test, see [0007](0007-architecture-test-with-shrinking-baseline.md)). This includes information +that is only needed to present the solution, such as the time zone, device IDs, the start of the +run and the prediction series the run was optimized against. + +## Considered Options + +- **Let the solution conversion read the configuration and predictions**: rejected. A prediction + update during the run pairs the solution with a forecast it was not optimized for, and display + details such as the time zone can change between preparation and conversion as well. + +## Consequences + +- An optimizer can be run, tested and replayed from a stored set of optimization parameters alone. +- The optimization parameters grow to carry presentation data (time zone, device IDs, start + datetime, the prediction series used). diff --git a/docs/adr/0004-optimizers-duplicate-code-instead-of-sharing-it.md b/docs/adr/0004-optimizers-duplicate-code-instead-of-sharing-it.md new file mode 100644 index 00000000..4ce6ebdc --- /dev/null +++ b/docs/adr/0004-optimizers-duplicate-code-instead-of-sharing-it.md @@ -0,0 +1,35 @@ +# Optimizers duplicate code instead of sharing it + +Each optimizer must be removable, and must keep its results, when another optimizer is changed or +removed. So dependencies run one way only. An optimizer may import generic utilities (such as +`datetimeutil`; Pydantic only where +[0009](0009-optimization-parameters-are-dataclasses.md) allows it), the output contract (the optimization solution and +the energy management plan) and, in its parameter preparation only, the configuration settings +(including the shared operation-mode enums and settings-side resolution such as battery profiles), +predictions and measurements. It never imports another optimizer, and it does not share simulation +physics: helpers such as efficiency curve interpolation or the AC/DC energy solvers are copied into +each optimizer that needs them. Code outside an optimizer never imports the optimizer's internals; +converting device settings into an optimizer's device parameters is part of that optimizer's +parameter preparation, not of the settings: the shared device configuration never imports an +optimizer, not even its package. + +## Considered Options + +- **Shared simulation physics in `devicesabc`**: rejected. A fix or model change for one optimizer + would silently change the results of the others, and no optimizer could be reasoned about alone. +- **Settings that build each optimizer's parameters (`to_genetic_parameters()` and similar)**: + rejected. It makes the configuration depend on every optimizer, so removing one breaks the + settings. + +## Consequences + +- Duplicated code is deliberate. Do not merge copies of simulation code across optimizers to + remove the duplication; a fix in one copy is applied to another only by a deliberate change to + that optimizer. +- The output contract still lives in `optimization/optimization.py` together with + `OptimizationCommonSettings`; it moves to a module of its own during the migration. Until then + only the contract classes (`OptimizationSolution`) may be imported from there outside parameter + preparation; the architecture test lists them. +- The operation-mode enums and settings-side resolution stay shared because they describe the + configuration, not an optimizer; an optimizer translates them into its own types during + parameter preparation. diff --git a/docs/adr/0005-optimizers-plug-in-through-one-registry.md b/docs/adr/0005-optimizers-plug-in-through-one-registry.md new file mode 100644 index 00000000..ff707a55 --- /dev/null +++ b/docs/adr/0005-optimizers-plug-in-through-one-registry.md @@ -0,0 +1,26 @@ +# Optimizers plug in through one registry + +Removing an optimizer must not require changes all over the code base. So every optimizer +implements the same small interface and is listed in one registry; the energy management, the +server and EOSdash use only the registry and the interface and never name a specific optimizer. +An optimizer is one directory, `optimization//` +([0010](0010-one-directory-and-one-naming-scheme-per-optimizer.md)); outside code imports only its +package itself (`__init__.py`), which exports what the registry and the settings field need. +The optimizer's package owns everything specific to it: its settings model +(`optimization.`) including the validation of its horizons, its parameter preparation, run +and solution conversion, its own REST endpoints (contributed as a router), its visualization and +its wizard steps and its simulation devices. Removing an optimizer touches exactly four places in +the production code: its package, its registry entry, its settings field in +`OptimizationCommonSettings`, and a configuration migration step that drops `optimization.` +from existing configurations and switches `optimization.algorithm` to a remaining optimizer. What +belongs only to the optimizer goes with it: its tests, its test data and, while the baseline of the +architecture test ([0007](0007-architecture-test-with-shrinking-baseline.md)) still lists +violations of the optimizer, their entries. The tests of the remaining optimizers pass unchanged. + +## Considered Options + +- **Settings fields added dynamically from the registry**: rejected. A Pydantic model assembled at + runtime is harder to type-check and to document; a static field per optimizer costs one more + line to delete on removal. +- **One branch per optimizer in the energy management and the server**: rejected. Each new or + removed optimizer would touch shared code, and the branches drift apart. diff --git a/docs/adr/0006-optimizer-interface-prepare-run-convert.md b/docs/adr/0006-optimizer-interface-prepare-run-convert.md new file mode 100644 index 00000000..21d2fb6e --- /dev/null +++ b/docs/adr/0006-optimizer-interface-prepare-run-convert.md @@ -0,0 +1,47 @@ +# Optimizers implement prepare, run and convert + +Every optimizer follows the same three-step interface, so the energy management can drive any of +them the same way and every run can be replayed from its optimization parameters. The interface is +a `Protocol` generic in the optimizer's optimization parameters `P`, optimization request `Q` and +optimization result `R`, with `prepare()` and `prepare_from_request()` (asynchronous, given the run +start and the warm start), `run()` and `convert()`, the latter returning the optimization solution +and the energy management plan. Its current signature is kept in one place, the +`optimizer-architecture` skill (`ai/skills/optimizer-architecture/SKILL.md`). + +- `prepare()` is the parameter preparation. It never fails and never returns `None` (see the + `energy-domain` skill); the energy management never cancels a run because of it. +- `run()` is CPU-bound and deterministic: the same optimization parameters give the same result. + All algorithm settings (generations, individuals, seed, penalties) are part of the optimization + parameters; a REST override such as `?ngen=` is applied to the parameters before `run()`. +- `convert()` is the solution conversion and uses only the parameters and the result. + +The energy management is the only owner of run state. It keeps the last result per optimizer and +passes the run start and that result (the warm start) to `prepare()` as arguments, so no part of an +optimizer reads EMS state; the warm start and its start datetime travel into `run()` inside the +optimization parameters. + +Optimization requests from clients (the parameters accepted by `POST /optimize` and the GENETIC0 +legacy endpoint, and `ConfigOptimizationRequest`) never go straight into `run()`. They keep their +public schema (`Q`) and go through the optimizer's parameter preparation, +`prepare_from_request()`, which fills everything the +request does not carry (time zone, device IDs, algorithm settings) from the configuration and +applies the same fallback rules as `prepare()`. A malformed request is still rejected (422) before +preparation; a request that is valid but incomplete is completed, never rejected. So `run()` and +`convert()` only ever see complete optimization parameters, whatever the entry point. + +## Considered Options + +- **Preparation reads the previous result from the energy management**: rejected. It keeps the + optimizer coupled to EMS internals (today `get_ems().genetic_solution()`), and a run cannot be + reproduced from its parameters alone. +- **Algorithm settings passed beside the parameters**: rejected. A stored parameter set would not + be enough to replay a run. +- **Clients send complete optimization parameters**: rejected. The presentation data required by + [0003](0003-optimizers-see-only-their-optimization-parameters.md) would break every existing + client of the public API. + +## Consequences + +- The energy management stores results per optimizer in one generic slot, not one attribute per + optimizer. +- An optimization run that cannot be reproduced from its stored optimization parameters is a bug. diff --git a/docs/adr/0007-architecture-test-with-shrinking-baseline.md b/docs/adr/0007-architecture-test-with-shrinking-baseline.md new file mode 100644 index 00000000..f66734dc --- /dev/null +++ b/docs/adr/0007-architecture-test-with-shrinking-baseline.md @@ -0,0 +1,47 @@ +# An architecture test with a shrinking baseline enforces the optimizer boundaries + +The optimizer rules ([0003](0003-optimizers-see-only-their-optimization-parameters.md) to +[0006](0006-optimizer-interface-prepare-run-convert.md)) are mostly import rules, and a skill alone +does not stop an agent or a contributor from breaking them. So `tests/test_optimizerarchitecture.py` +parses the imports of the source tree with `ast` and fails when + +- an optimizer imports another optimizer, +- code outside an optimizer imports anything from it but its packages themselves (`__init__.py`), +- the shared device configuration imports an optimizer at all, so settings cannot build optimization + parameters ([0004](0004-optimizers-duplicate-code-instead-of-sharing-it.md)), +- a module of an optimizer other than its parameter preparation imports a module or name that + reads configuration, predictions, measurements or EMS state, +- parameter preparation imports EMS state or the server, +- a module of an optimizer other than `optimizer.py`, its package `__init__.py` and the + parameter preparation itself imports the parameter preparation, the optimizer's own package or + `optimizer.py` (both may re-export it; only the package imports `optimizer.py`), so + no other module reaches the configuration through it, +- a module other than settings, request, preparation and API + ([0010](0010-one-directory-and-one-naming-scheme-per-optimizer.md)) imports Pydantic + ([0009](0009-optimization-parameters-are-dataclasses.md)). + +The test holds the one authoritative list of these modules and names, including helpers that read +the configuration, the server (`akkudoktoreos.server`, +[0011](0011-optimizer-api-visualization-and-wizard-get-no-exception.md)), the shared device +configuration (`devices.settings`, `devices.profile`, `devices.devices`, `devices.devicesabc`) and +the contract classes that may be imported from a module that mixes them with configuration +(`optimization.optimization`). Parameter preparation is recognized by its file name, +`optimization//prepare.py` or a subpackage `optimization//prepare/` (a plain +module `prepare.py` does not count); the settings +model `optimization//settings.py` may import `config.configabc` to define +`optimization.`. The test discovers the optimizers (every package under `optimization/`), so +adding one does not touch it; until the simulation devices have moved into the optimizer +directory, `devices/` counts as part of the optimizer. + +The violations that exist when the test lands are listed in a baseline in the test file. A +violation missing from the baseline fails, and so does a baseline entry that no longer occurs, so +the baseline only shrinks and every exception is visible in review. The one exception: when a +module or helper that reads the configuration is added to the list, the existing uses it reveals +are added to the baseline in the same commit. The test cannot see simulation physics moved into a +new shared module, nor a helper missing from its list; both rely on review. + +## Considered Options + +- **`import-linter`**: rejected, it adds a dependency for checks a short `ast` walk can do. +- **Refactor first, then add the test without a baseline**: rejected, the boundaries would stay + unprotected for the whole migration. diff --git a/docs/adr/0008-optimizer-refactoring-preserves-results.md b/docs/adr/0008-optimizer-refactoring-preserves-results.md new file mode 100644 index 00000000..37820883 --- /dev/null +++ b/docs/adr/0008-optimizer-refactoring-preserves-results.md @@ -0,0 +1,21 @@ +# Optimizer refactoring preserves results, and GENETIC0 is frozen + +An optimization result is a charge schedule for real devices, so a refactoring that silently +changes results is a defect in production, not a code-quality issue. Refactoring an optimizer, +including the migration to the architecture of ADRs +[0003](0003-optimizers-see-only-their-optimization-parameters.md) to +[0007](0007-architecture-test-with-shrinking-baseline.md), is therefore behaviour-preserving: with +a fixed seed every stored input gives the same solution as before. A change that alters a golden +result (`tests/testdata//optimize_result_*.json` or a replay file) is a behaviour +change and goes in its own, explicitly declared pull request; a refactoring pull request never +regenerates golden data. GENETIC0 is frozen: its results never change. It gets no bug fixes and no +behaviour changes, only the structural changes needed to follow the optimizer architecture, each +proven result-identical by its golden tests. + +## Consequences + +- Before an optimizer is refactored, its golden tests are extended with replay files: complete + optimization parameters in the new parameter type plus the expected result. +- GENETIC0 is migrated first, as the pilot; the registry and the interface arrive with its first + migration pull request. GENETIC follows. +- A GENETIC0 bug that matters to users is fixed in GENETIC (or a new optimizer), not in GENETIC0. diff --git a/docs/adr/0009-optimization-parameters-are-dataclasses.md b/docs/adr/0009-optimization-parameters-are-dataclasses.md new file mode 100644 index 00000000..320a1ddf --- /dev/null +++ b/docs/adr/0009-optimization-parameters-are-dataclasses.md @@ -0,0 +1,23 @@ +# Optimization parameters are dataclasses, optimization requests are Pydantic models + +The optimization parameters are read in the innermost loops of an optimization run, and they no +longer cross the public API: clients send optimization requests, which parameter preparation +completes into optimization parameters ([0006](0006-optimizer-interface-prepare-run-convert.md)). +So the optimization parameters, including the device parameters of the simulation, are plain +Python dataclasses (`@dataclass(frozen=True, slots=True)`: a run never changes its inputs, and +slots keep attribute access fast), never Pydantic models; they are valid by construction because parameter +preparation always builds a valid set (see the `energy-domain` skill), not because a model +validates them. Validation and the public schema live where external input arrives: optimization +requests are Pydantic models, and the settings models of the configuration stay Pydantic models. + +## Considered Options + +- **Pydantic models for the optimization parameters**: rejected. Attribute access and copies of + Pydantic models cost time in the run, and the validation they offer is redundant behind a + parameter preparation that never produces an invalid set. + +## Consequences + +- An invalid optimization parameter set is a bug in parameter preparation, found by its tests, + not a validation error at run time. +- Replay files need an explicit (de)serialization of the dataclasses instead of Pydantic's. diff --git a/docs/adr/0010-one-directory-and-one-naming-scheme-per-optimizer.md b/docs/adr/0010-one-directory-and-one-naming-scheme-per-optimizer.md new file mode 100644 index 00000000..5d19ce9f --- /dev/null +++ b/docs/adr/0010-one-directory-and-one-naming-scheme-per-optimizer.md @@ -0,0 +1,26 @@ +# One directory and one naming scheme per optimizer + +Removing an optimizer ([0005](0005-optimizers-plug-in-through-one-registry.md)) and telling the +optimizers apart in code, tracebacks and search results is easiest when every optimizer has the +same shape. So everything that belongs to an optimizer, its simulation devices included, lives in +one directory `src/akkudoktoreos/optimization//`, named after the optimizer in lowercase +(`genetic`, `genetic0`). Its simulation devices live in the subdirectory `devices/`; the top-level +`devices/` package keeps only the shared device configuration (`settings/`, `profile/`, +`devices.py`, `devicesabc.py`). Every module is named `.py` and every class +``, with one fixed set of roles: settings, request, parameters, preparation, optimizer, +algorithm, result, simulation (with its devices), conversion, visualization and API. The table of +roles with their modules, classes and kinds is kept in one place, the `optimizer-architecture` +skill (`ai/skills/optimizer-architecture/SKILL.md`). + +The package's `__init__.py` is the only module outside code imports. Further modules that do not +fit a role use the `` prefix as well, also inside subdirectories such as `devices/` or a +`prepare/` subpackage for a large parameter preparation. + +## Consequences + +- The public classes are renamed (e.g. `GeneticOptimizationParameters` → `GeneticRequest`, + `GeneticCommonSettings` → `GeneticSettings`). Field names and payloads stay unchanged; the + schema names in OpenAPI and the configuration documentation change. +- `devices/genetic/` and `devices/genetic0/` move into the optimizer directories. For the frozen + GENETIC0 ([0008](0008-optimizer-refactoring-preserves-results.md)) the moves and renames are + structural changes, proven by its golden tests. diff --git a/docs/adr/0011-optimizer-api-visualization-and-wizard-get-no-exception.md b/docs/adr/0011-optimizer-api-visualization-and-wizard-get-no-exception.md new file mode 100644 index 00000000..748561e1 --- /dev/null +++ b/docs/adr/0011-optimizer-api-visualization-and-wizard-get-no-exception.md @@ -0,0 +1,27 @@ +# Optimizer API, visualization and wizard steps get no exception + +An optimizer owns its REST endpoints, its visualization and its EOSdash wizard steps +([0005](0005-optimizers-plug-in-through-one-registry.md)), and all three read configuration or EMS +state today. None of them gets an exception from +[0003](0003-optimizers-see-only-their-optimization-parameters.md): + +- The visualization (`visualize.py`) is part of the solution conversion and renders from the + optimization parameters and the optimization result only. +- The REST router (`api.py`) never fetches anything itself. It declares placeholder + dependency functions for what it needs: the optimizer's last optimization parameters and result, + kept by the energy management, and the call that starts a run. The generic server fills them in + through FastAPI's `app.dependency_overrides`, using the registry. The router may import FastAPI, + Pydantic and its own optimization request, never configuration, EMS state or the server + (`akkudoktoreos.server`). No other part of the optimizer, its parameter preparation included, + imports the server either. +- Wizard steps are not code. They are metadata on the fields of `settings.py` (which fields + the wizard asks for, and in which order), which EOSdash reads; an optimizer contains no EOSdash + code. + +## Considered Options + +- **An "integration" role that may read configuration and EMS state**: rejected. It would become + the place where optimizer code quietly reaches the outside world again, and removing an + optimizer would still mean finding its integration code in the server and EOSdash. +- **The router imports its dependency functions from the server**: rejected. The optimizer would + depend on the server, and a server helper is an easy way back to the configuration. diff --git a/docs/develop/ai.md b/docs/develop/ai.md index 9d4ce6ee..2f7579f2 100644 --- a/docs/develop/ai.md +++ b/docs/develop/ai.md @@ -54,6 +54,7 @@ Agents get their project knowledge from two places in the repository: | `filename-conventions` | File name rules enforced by `scripts/lint_filenames.py` | | `application-configuration` | Configuration models, defaults and migration | | `energy-domain` | Optimization, adapters, units and sign conventions | +| `optimizer-architecture` | Optimizer structure, boundaries and independence | | `rest-api` | REST endpoints and error responses | | `commit-messages` | Conventional Commits as checked by `commitizen` | diff --git a/tests/test_optimizerarchitecture.py b/tests/test_optimizerarchitecture.py new file mode 100644 index 00000000..88d4cb57 --- /dev/null +++ b/tests/test_optimizerarchitecture.py @@ -0,0 +1,1106 @@ +"""Architecture test for the optimizer boundaries (ADR 0003 to 0011). + +Parses the imports of ``src/akkudoktoreos`` and checks these rules: + +- ``cross-optimizer``: an optimizer never imports another optimizer. +- ``internals``: code outside an optimizer imports only the optimizer's package + (its ``__init__.py``), never its modules. +- ``shared-config``: the shared device configuration never imports an + optimizer, not even its package; settings do not build optimization + parameters (ADR 0004). +- ``world-access``: only the parameter preparation of an optimizer + (``prepare.py`` or a ``prepare`` subpackage) reads configuration, + predictions and measurements; no module of an optimizer, the preparation + included, reads EMS state or the server. The optimizer's settings model + (``settings.py``) may import ``akkudoktoreos.config.configabc`` to define + ``optimization.``. +- ``preparation``: inside an optimizer only ``optimizer.py``, the + package ``__init__.py`` and the parameter preparation itself import the + parameter preparation, so no other module reaches the configuration through + it. The package and ``optimizer.py`` may re-export the preparation, so + the other modules import neither; only the package imports + ``optimizer.py``. +- ``pydantic``: only the settings, request, preparation and API modules of an + optimizer import Pydantic; optimization parameters are dataclasses. + +Violations that existed when the test was introduced are listed in +``BASELINE``. The baseline only shrinks: a violation missing from it fails, and +so does an entry that no longer occurs. Remove the entries a change fixes. Add +entries only together with a new entry in the lists below, for the existing +uses it reveals (ADR 0007). +""" + +import ast +import functools +import os +from pathlib import Path +from typing import Callable, Iterable, Iterator, Mapping, NamedTuple, Optional + +import pytest + +PACKAGE = "akkudoktoreos" +SRC_DIR = Path(__file__).parent.parent / "src" + +Optimizers = Mapping[str, tuple[str, ...]] + + +def _exists_as_named(path: Path, root: Path) -> bool: + """``path`` exists below ``root`` with exactly this spelling of each of its parts. + + ``Path.exists()`` ignores case on case-insensitive file systems (Windows, + macOS), where ``GeneticOptimizer`` would match ``geneticoptimizer.py``; the + directory listing keeps the spelling. + """ + current = root + for part in path.relative_to(root).parts: + if not current.is_dir() or part not in os.listdir(current): + return False + current = current / part + return True + + +def _is_package(path: Path, root: Path = SRC_DIR) -> bool: + """A regular or namespace package: a directory holding Python modules.""" + return _exists_as_named(path, root) and path.is_dir() and any(path.rglob("*.py")) + + +def _is_module(module: str, src_dir: Path = SRC_DIR) -> bool: + path = src_dir / Path(*module.split(".")) + module_file = path.with_suffix(".py") + return (_exists_as_named(module_file, src_dir) and module_file.is_file()) or _is_package( + path, src_dir + ) + + +def _discover_optimizers(src_dir: Path = SRC_DIR) -> dict[str, tuple[str, ...]]: + """Optimizer name -> packages that belong to it. + + Every subpackage ``optimization/`` is an optimizer; ``devices/`` + holds its simulation devices, if present. Discovered, so that adding or + removing an optimizer does not touch this test. + """ + optimizers: dict[str, tuple[str, ...]] = {} + for path in sorted((src_dir / PACKAGE / "optimization").iterdir()): + if not _is_package(path, src_dir): + continue + name = path.name + packages = [f"{PACKAGE}.optimization.{name}"] + if _is_module(f"{PACKAGE}.devices.{name}", src_dir): + packages.append(f"{PACKAGE}.devices.{name}") + optimizers[name] = tuple(packages) + return optimizers + + +OPTIMIZERS: dict[str, tuple[str, ...]] = _discover_optimizers() + +# Modules an optimizer reads only during parameter preparation: configuration, +# predictions, measurements, EMS state, the server, and the shared device +# configuration (device settings, profiles, operation-mode enums). +WORLD_MODULES: tuple[str, ...] = ( + "akkudoktoreos.config", + "akkudoktoreos.prediction", + "akkudoktoreos.measurement", + "akkudoktoreos.core.ems", + "akkudoktoreos.core.emsettings", + "akkudoktoreos.core.cachesettings", + "akkudoktoreos.core.logsettings", + "akkudoktoreos.core.database", + "akkudoktoreos.core.databaseabc", + "akkudoktoreos.core.dataabc", + "akkudoktoreos.core.cache", + "akkudoktoreos.adapter", + "akkudoktoreos.server", + "akkudoktoreos.devices.settings", + "akkudoktoreos.devices.profile", + "akkudoktoreos.devices.devices", + "akkudoktoreos.devices.devicesabc", +) + +# Names that give access to configuration, predictions, measurements or EMS state. +WORLD_NAMES: dict[str, frozenset[str]] = { + "akkudoktoreos.core.coreabc": frozenset( + { + "ConfigMixin", + "PredictionMixin", + "MeasurementMixin", + "EnergyManagementSystemMixin", + "get_config", + "get_prediction", + "get_measurement", + "get_ems", + "StartMixin", + "DatabaseMixin", + "get_database", + "AdapterMixin", + "get_adapter", + "get_resource_registry", + "config_initialized", + "singletons_init", + } + ), + "akkudoktoreos.optimization.optimizationabc": frozenset({"OptimizationBase"}), + "akkudoktoreos.utils.gridinterpolator": frozenset({"configured_grid_interpolator_backend"}), +} + +# Modules that mix the output contract with configuration: outside parameter +# preparation an optimizer imports only the listed contract names (ADR 0004). +CONTRACT_NAMES: dict[str, frozenset[str]] = { + "akkudoktoreos.optimization.optimization": frozenset({"OptimizationSolution"}), +} + +# EMS state and the server, banned in parameter preparation too: the energy +# management passes the run start and the warm start as arguments (ADR 0006), +# and the optimizer never imports server code (ADR 0011). +PREPARATION_BANNED_MODULES: tuple[str, ...] = ( + "akkudoktoreos.core.ems", + "akkudoktoreos.core.cache", + "akkudoktoreos.server", +) +PREPARATION_BANNED_NAMES: dict[str, frozenset[str]] = { + "akkudoktoreos.core.coreabc": frozenset( + {"EnergyManagementSystemMixin", "StartMixin", "get_ems"} + ), +} + +# The shared device configuration: never imports an optimizer (ADR 0004). +SHARED_CONFIG_MODULES: tuple[str, ...] = ( + "akkudoktoreos.devices.settings", + "akkudoktoreos.devices.profile", + "akkudoktoreos.devices.devices", + "akkudoktoreos.devices.devicesabc", +) + +# Pydantic, allowed only where external input arrives (ADR 0009, 0010). +PYDANTIC_MODULES: tuple[str, ...] = ("pydantic", "akkudoktoreos.core.pydantic") +PYDANTIC_ROLES: tuple[str, ...] = ("settings", "request", "api") + +# What an optimizer's settings model may import beyond the generic rules. +SETTINGS_ALLOWED_MODULES: tuple[str, ...] = ("akkudoktoreos.config.configabc",) + + +class Violation(NamedTuple): + """One import that breaks an optimizer boundary.""" + + rule: str + module: str + imported: str + + +def _within(module: str, package: str) -> bool: + return module == package or module.startswith(package + ".") + + +def _within_any(module: str, packages: Iterable[str]) -> bool: + return any(_within(module, package) for package in packages) + + +def _module_name(path: Path, src_dir: Path = SRC_DIR) -> str: + parts = list(path.relative_to(src_dir).with_suffix("").parts) + if parts[-1] == "__init__": + parts.pop() + return ".".join(parts) + + +def _optimizer_of(module: str, optimizers: Optimizers) -> Optional[str]: + for name, packages in optimizers.items(): + if _within_any(module, packages): + return name + return None + + +def _is_preparation(module: str, optimizer: str, src_dir: Path = SRC_DIR) -> bool: + """``optimization//prepare.py`` or a package ``optimization//prepare/``.""" + package = f"akkudoktoreos.optimization.{optimizer}" + subpackage = f"{package}.prepare" + return ( + module == f"{package}.{optimizer}prepare" + or module.startswith(subpackage + ".") + or (module == subpackage and _is_package(src_dir / Path(*subpackage.split(".")), src_dir)) + ) + + +def _has_role(module: str, optimizer: str, role: str) -> bool: + """Module ``optimization//.py`` (ADR 0010).""" + return module == f"akkudoktoreos.optimization.{optimizer}.{optimizer}{role}" + + +def _names_hit(names: Mapping[str, frozenset[str]], source: str, name: str) -> bool: + """``source:name`` is one of ``names``; ``*`` hits every module that has some.""" + listed = names.get(source, frozenset()) + return name in listed or (name == "*" and bool(listed)) + + +def _imports(path: Path, module: str) -> Iterator[str]: + """Yield every imported module, and ``module:name`` for each imported name. + + A module bound as a whole (``import a.b``, ``from a import b`` for a module + ``b``, ``from a import *``) also yields ``module:*``: every name in it is + reachable. Function-level and ``TYPE_CHECKING`` imports count: they are + dependencies as well. + """ + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + package = module if path.name == "__init__.py" else module.rsplit(".", 1)[0] + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + yield alias.name + yield f"{alias.name}:*" + elif isinstance(node, ast.ImportFrom): + if node.level: + base = package.split(".") + base = base[: len(base) - (node.level - 1)] + source = ".".join(base + ([node.module] if node.module else [])) + else: + source = node.module or "" + for alias in node.names: + submodule = f"{source}.{alias.name}" + if _is_module(submodule): + # Depends on the submodule, not on everything in ``source``. + yield submodule + yield f"{submodule}:*" + else: + yield source + yield f"{source}:{alias.name}" + + +def _check(module: str, imported: str, optimizers: Optimizers) -> Iterator[Violation]: + source, _, name = imported.partition(":") + own = _optimizer_of(module, optimizers) + if ( + own is not None + and not name + and _within_any(source, PYDANTIC_MODULES) + and not _is_preparation(module, own) + and not any(_has_role(module, own, role) for role in PYDANTIC_ROLES) + ): + yield Violation("pydantic", module, source) + if not _within(source, PACKAGE): + return + other = _optimizer_of(source, optimizers) + + if own is None: + if other is None: + return + if _within_any(module, SHARED_CONFIG_MODULES): + # Settings never build an optimizer's parameters. + yield Violation("shared-config", module, source) + elif source not in optimizers[other]: + # Outside code may import an optimizer's package, not its modules. + yield Violation("internals", module, source) + return + + if other is not None and other != own: + yield Violation("cross-optimizer", module, source) + return + + if _is_preparation(module, own): + if _names_hit(PREPARATION_BANNED_NAMES, source, name) or ( + not name and _within_any(source, PREPARATION_BANNED_MODULES) + ): + yield Violation("world-access", module, imported if name else source) + return + # The preparation and the modules that may re-export it: the package and + # optimizer.py. Only the package imports the optimizer module. + package = f"akkudoktoreos.optimization.{own}" + source_is_optimizer = _has_role(source, own, "optimizer") + if not name and (_is_preparation(source, own) or source == package or source_is_optimizer): + if module != package and not ( + _has_role(module, own, "optimizer") and not source_is_optimizer + ): + yield Violation("preparation", module, source) + return + if name: + if _names_hit(WORLD_NAMES, source, name) or ( + source in CONTRACT_NAMES and name not in CONTRACT_NAMES[source] + ): + yield Violation("world-access", module, imported) + return + if _within_any(source, WORLD_MODULES): + if _has_role(module, own, "settings") and _within_any(source, SETTINGS_ALLOWED_MODULES): + return + yield Violation("world-access", module, source) + + +@functools.cache +def collect_violations() -> frozenset[Violation]: + """All boundary violations in the source tree.""" + violations: set[Violation] = set() + for path in sorted((SRC_DIR / PACKAGE).rglob("*.py")): + module = _module_name(path) + for imported in _imports(path, module): + violations.update(_check(module, imported, OPTIMIZERS)) + return frozenset(violations) + + +# Known violations when the test was introduced. Remove fixed entries; add only +# the existing uses revealed by a new list entry (ADR 0007). +BASELINE: frozenset[Violation] = frozenset( + { + Violation( + "cross-optimizer", + "akkudoktoreos.optimization.genetic0.genetic0params", + "akkudoktoreos.optimization.genetic.forecast", + ), + Violation( + "internals", + "akkudoktoreos.config.configmigrate", + "akkudoktoreos.optimization.genetic.geneticsettings", + ), + Violation( + "internals", + "akkudoktoreos.core.ems", + "akkudoktoreos.optimization.genetic.configrequest", + ), + Violation( + "internals", + "akkudoktoreos.core.ems", + "akkudoktoreos.optimization.genetic.genetic", + ), + Violation( + "internals", + "akkudoktoreos.core.ems", + "akkudoktoreos.optimization.genetic.geneticparams", + ), + Violation( + "internals", + "akkudoktoreos.core.ems", + "akkudoktoreos.optimization.genetic.geneticsolution", + ), + Violation( + "internals", + "akkudoktoreos.core.ems", + "akkudoktoreos.optimization.genetic0.genetic0", + ), + Violation( + "internals", + "akkudoktoreos.core.ems", + "akkudoktoreos.optimization.genetic0.genetic0params", + ), + Violation( + "internals", + "akkudoktoreos.core.ems", + "akkudoktoreos.optimization.genetic0.genetic0solution", + ), + Violation( + "internals", + "akkudoktoreos.optimization.optimization", + "akkudoktoreos.optimization.genetic.geneticsettings", + ), + Violation( + "internals", + "akkudoktoreos.optimization.optimization", + "akkudoktoreos.optimization.genetic0.genetic0settings", + ), + Violation( + "internals", + "akkudoktoreos.server.eos", + "akkudoktoreos.optimization.genetic.configrequest", + ), + Violation( + "internals", + "akkudoktoreos.server.eos", + "akkudoktoreos.optimization.genetic.geneticsolution", + ), + Violation( + "internals", + "akkudoktoreos.server.eos", + "akkudoktoreos.optimization.genetic.geneticvisualize", + ), + Violation( + "internals", + "akkudoktoreos.server.eos", + "akkudoktoreos.optimization.genetic0.genetic0params", + ), + Violation( + "internals", + "akkudoktoreos.server.eos", + "akkudoktoreos.optimization.genetic0.genetic0solution", + ), + Violation( + "internals", + "akkudoktoreos.server.eos", + "akkudoktoreos.optimization.genetic0.genetic0visualize", + ), + Violation( + "pydantic", + "akkudoktoreos.devices.genetic.battery", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.devices.genetic.homeappliance", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.devices.genetic.inverter", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.devices.genetic0.genetic0battery", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.devices.genetic0.genetic0homeappliance", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.devices.genetic0.genetic0inverter", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic.configrequest", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic.genetic", + "akkudoktoreos.core.pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic.genetic", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic.geneticabc", + "akkudoktoreos.core.pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic.geneticabc", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic.geneticdevices", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic.geneticparams", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic.geneticsolution", + "akkudoktoreos.core.pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic.geneticsolution", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic.tailvalue", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic.terminalvalue", + "akkudoktoreos.core.pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic.terminalvalue", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic0.genetic0", + "akkudoktoreos.core.pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic0.genetic0", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic0.genetic0abc", + "akkudoktoreos.core.pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic0.genetic0abc", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic0.genetic0devices", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic0.genetic0params", + "pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic0.genetic0solution", + "akkudoktoreos.core.pydantic", + ), + Violation( + "pydantic", + "akkudoktoreos.optimization.genetic0.genetic0solution", + "pydantic", + ), + Violation( + "shared-config", + "akkudoktoreos.devices.settings.batterysettings", + "akkudoktoreos.devices.genetic.battery", + ), + Violation( + "shared-config", + "akkudoktoreos.devices.settings.batterysettings", + "akkudoktoreos.devices.genetic0.genetic0battery", + ), + Violation( + "shared-config", + "akkudoktoreos.devices.settings.homeappliancesettings", + "akkudoktoreos.devices.genetic.homeappliance", + ), + Violation( + "shared-config", + "akkudoktoreos.devices.settings.homeappliancesettings", + "akkudoktoreos.devices.genetic0.genetic0homeappliance", + ), + Violation( + "shared-config", + "akkudoktoreos.devices.settings.invertersettings", + "akkudoktoreos.devices.genetic.inverter", + ), + Violation( + "shared-config", + "akkudoktoreos.devices.settings.invertersettings", + "akkudoktoreos.devices.genetic0.genetic0inverter", + ), + Violation( + "world-access", + "akkudoktoreos.devices.genetic.battery", + "akkudoktoreos.devices.devicesabc", + ), + Violation( + "world-access", + "akkudoktoreos.devices.genetic.battery", + "akkudoktoreos.devices.settings.batteryresolution", + ), + Violation( + "world-access", + "akkudoktoreos.devices.genetic.battery", + "akkudoktoreos.devices.settings.batterysettings", + ), + Violation( + "world-access", + "akkudoktoreos.devices.genetic.homeappliance", + "akkudoktoreos.config.configabc", + ), + Violation( + "world-access", + "akkudoktoreos.devices.genetic.homeappliance", + "akkudoktoreos.devices.devicesabc", + ), + Violation( + "world-access", + "akkudoktoreos.devices.genetic.inverter", + "akkudoktoreos.devices.devicesabc", + ), + Violation( + "world-access", + "akkudoktoreos.devices.genetic.inverter", + "akkudoktoreos.prediction.interpolator", + ), + Violation( + "world-access", + "akkudoktoreos.devices.genetic0.genetic0battery", + "akkudoktoreos.devices.settings.batterysettings", + ), + Violation( + "world-access", + "akkudoktoreos.devices.genetic0.genetic0homeappliance", + "akkudoktoreos.config.configabc", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.configrequest", + "akkudoktoreos.core.coreabc:ConfigMixin", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.configrequest", + "akkudoktoreos.core.coreabc:MeasurementMixin", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.configrequest", + "akkudoktoreos.core.coreabc:PredictionMixin", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.configrequest", + "akkudoktoreos.core.coreabc:get_ems", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.configrequest", + "akkudoktoreos.devices.settings.batteryresolution", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.configrequest", + "akkudoktoreos.devices.settings.batterysettings", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.genetic", + "akkudoktoreos.devices.devicesabc", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.genetic", + "akkudoktoreos.optimization.optimizationabc:OptimizationBase", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.geneticparams", + "akkudoktoreos.core.coreabc:ConfigMixin", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.geneticparams", + "akkudoktoreos.core.coreabc:MeasurementMixin", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.geneticparams", + "akkudoktoreos.core.coreabc:PredictionMixin", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.geneticsolution", + "akkudoktoreos.core.coreabc:ConfigMixin", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.geneticsolution", + "akkudoktoreos.core.coreabc:get_ems", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.geneticsolution", + "akkudoktoreos.core.coreabc:get_prediction", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.geneticsolution", + "akkudoktoreos.devices.devicesabc", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.geneticvisualize", + "akkudoktoreos.core.coreabc:ConfigMixin", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic.geneticvisualize", + "akkudoktoreos.core.coreabc:get_ems", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic0.genetic0", + "akkudoktoreos.optimization.optimizationabc:OptimizationBase", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic0.genetic0loadinterpolator", + "akkudoktoreos.core.cache", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic0.genetic0loadinterpolator", + "akkudoktoreos.utils.gridinterpolator:configured_grid_interpolator_backend", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic0.genetic0params", + "akkudoktoreos.core.coreabc:ConfigMixin", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic0.genetic0params", + "akkudoktoreos.core.coreabc:MeasurementMixin", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic0.genetic0params", + "akkudoktoreos.core.coreabc:PredictionMixin", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic0.genetic0params", + "akkudoktoreos.core.coreabc:get_ems", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic0.genetic0solution", + "akkudoktoreos.core.coreabc:ConfigMixin", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic0.genetic0solution", + "akkudoktoreos.core.coreabc:get_ems", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic0.genetic0solution", + "akkudoktoreos.core.coreabc:get_prediction", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic0.genetic0solution", + "akkudoktoreos.devices.devicesabc", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic0.genetic0visualize", + "akkudoktoreos.core.coreabc:ConfigMixin", + ), + Violation( + "world-access", + "akkudoktoreos.optimization.genetic0.genetic0visualize", + "akkudoktoreos.core.coreabc:get_ems", + ), + } +) + +# Made-up optimizers for the rule checks, so no real one is named in them. +SYNTHETIC_OPTIMIZERS: dict[str, tuple[str, ...]] = { + "alpha": ("akkudoktoreos.optimization.alpha", "akkudoktoreos.devices.alpha"), + "beta": ("akkudoktoreos.optimization.beta", "akkudoktoreos.devices.beta"), +} + + +def _format(violations: Iterable[Violation]) -> str: + return "\n".join(f" {v.rule}: {v.module} -> {v.imported}" for v in sorted(violations)) + + +def _write(path: Path, text: str = "") -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + + +class TestOptimizerArchitecture: + """Optimizer boundaries of ADR 0003 to 0011.""" + + def test_no_new_violations(self) -> None: + new = collect_violations() - BASELINE + assert not new, ( + "Imports break the optimizer boundaries (see the optimizer-architecture " + "skill and ADR 0003 to 0011). Fix the code; do not extend BASELINE for new code:\n" + + _format(new) + ) + + def test_baseline_has_no_stale_entries(self) -> None: + stale = BASELINE - collect_violations() + assert not stale, ( + "These baseline entries no longer occur. Remove them from BASELINE in " + "tests/test_optimizerarchitecture.py:\n" + _format(stale) + ) + + @pytest.mark.parametrize( + ("module", "imported", "rule"), + [ + # An optimizer importing another one. + ( + "akkudoktoreos.optimization.beta.betaparams", + "akkudoktoreos.optimization.alpha.forecast", + "cross-optimizer", + ), + # Outside code importing an optimizer's module. + ( + "akkudoktoreos.core.ems", + "akkudoktoreos.optimization.alpha.alpha", + "internals", + ), + # The shared device configuration importing an optimizer, even its package. + ( + "akkudoktoreos.devices.settings.batterysettings", + "akkudoktoreos.devices.alpha.battery", + "shared-config", + ), + ( + "akkudoktoreos.devices.devicesabc", + "akkudoktoreos.optimization.alpha", + "shared-config", + ), + # The simulation reading predictions. + ( + "akkudoktoreos.devices.alpha.inverter", + "akkudoktoreos.prediction.interpolator", + "world-access", + ), + # The solution conversion reading EMS state through a getter. + ( + "akkudoktoreos.optimization.alpha.alphasolution", + "akkudoktoreos.core.coreabc:get_ems", + "world-access", + ), + # A getter reached through the whole module. + ( + "akkudoktoreos.optimization.alpha.alpha", + "akkudoktoreos.core.coreabc:*", + "world-access", + ), + # EMS access through StartMixin. + ( + "akkudoktoreos.devices.alpha.battery", + "akkudoktoreos.core.coreabc:StartMixin", + "world-access", + ), + # The API or visualization reaching configuration through a server helper. + ( + "akkudoktoreos.optimization.alpha.alphaapi", + "akkudoktoreos.server.rest.error", + "world-access", + ), + # Configuration settings next to the output contract. + ( + "akkudoktoreos.optimization.alpha.alphaconvert", + "akkudoktoreos.optimization.optimization:OptimizationCommonSettings", + "world-access", + ), + ( + "akkudoktoreos.optimization.alpha.alphaconvert", + "akkudoktoreos.optimization.optimization:*", + "world-access", + ), + # A module that only ends in "prepare" is not parameter preparation. + ( + "akkudoktoreos.optimization.alpha.unprepare", + "akkudoktoreos.config.config", + "world-access", + ), + # Neither is a plain module prepare.py. + ( + "akkudoktoreos.optimization.alpha.prepare", + "akkudoktoreos.config.config", + "world-access", + ), + # Parameter preparation does not read EMS state either. + ( + "akkudoktoreos.optimization.alpha.alphaprepare", + "akkudoktoreos.core.coreabc:get_ems", + "world-access", + ), + ( + "akkudoktoreos.optimization.alpha.alphaprepare", + "akkudoktoreos.core.ems", + "world-access", + ), + # The EMS run cache, also banned in parameter preparation. + ( + "akkudoktoreos.optimization.alpha.alphaprepare", + "akkudoktoreos.core.cache", + "world-access", + ), + # Configuration read through a utility. + ( + "akkudoktoreos.optimization.alpha.alphainterpolator", + "akkudoktoreos.utils.gridinterpolator:configured_grid_interpolator_backend", + "world-access", + ), + # Configuration reached through the parameter preparation. + ( + "akkudoktoreos.optimization.alpha.alphaconvert", + "akkudoktoreos.optimization.alpha.alphaprepare", + "preparation", + ), + ( + "akkudoktoreos.optimization.alpha.alphavisualize", + "akkudoktoreos.optimization.alpha.prepare.alphadevices", + "preparation", + ), + # The parameter preparation reaching the server. + ( + "akkudoktoreos.optimization.alpha.alphaprepare", + "akkudoktoreos.server.rest.error", + "world-access", + ), + # The package may re-export the preparation. + ( + "akkudoktoreos.optimization.alpha.alphaconvert", + "akkudoktoreos.optimization.alpha", + "preparation", + ), + # The optimizer module may re-export the preparation. + ( + "akkudoktoreos.optimization.alpha.alphaconvert", + "akkudoktoreos.optimization.alpha.alphaoptimizer", + "preparation", + ), + ( + "akkudoktoreos.devices.alpha.battery", + "akkudoktoreos.optimization.alpha.alphaoptimizer", + "preparation", + ), + # Pydantic in the simulation. + ( + "akkudoktoreos.optimization.alpha.devices.alphabattery", + "pydantic", + "pydantic", + ), + ( + "akkudoktoreos.optimization.alpha.alphaparameters", + "akkudoktoreos.core.pydantic", + "pydantic", + ), + # Only the settings model under optimization/ may import config.configabc. + ( + "akkudoktoreos.devices.alpha.alphasettings", + "akkudoktoreos.config.configabc", + "world-access", + ), + ], + ) + def test_detects_violation(self, module: str, imported: str, rule: str) -> None: + assert [v.rule for v in _check(module, imported, SYNTHETIC_OPTIMIZERS)] == [rule] + + @pytest.mark.parametrize( + ("module", "imported"), + [ + # Parameter preparation reads the world. + ("akkudoktoreos.optimization.alpha.alphaprepare", "akkudoktoreos.config.config"), + ( + "akkudoktoreos.optimization.alpha.prepare.alphadevices", + "akkudoktoreos.config.config", + ), + ( + "akkudoktoreos.optimization.alpha.alphaprepare", + "akkudoktoreos.core.coreabc:get_prediction", + ), + ( + "akkudoktoreos.optimization.alpha.alphaprepare", + "akkudoktoreos.optimization.optimization:OptimizationCommonSettings", + ), + # The settings model defines optimization.. + ( + "akkudoktoreos.optimization.alpha.alphasettings", + "akkudoktoreos.config.configabc", + ), + # The optimizer, the package and the preparation itself use the preparation. + ( + "akkudoktoreos.optimization.alpha.alphaoptimizer", + "akkudoktoreos.optimization.alpha.alphaprepare", + ), + ( + "akkudoktoreos.optimization.alpha", + "akkudoktoreos.optimization.alpha.alphaprepare", + ), + ( + "akkudoktoreos.optimization.alpha.prepare.alphadevices", + "akkudoktoreos.optimization.alpha.alphaprepare", + ), + ( + "akkudoktoreos.optimization.alpha.alphaoptimizer", + "akkudoktoreos.optimization.alpha", + ), + ("akkudoktoreos.optimization.alpha", "akkudoktoreos.optimization.alpha.alphaoptimizer"), + # Generic utilities and the output contract. + ("akkudoktoreos.devices.alpha.battery", "akkudoktoreos.utils.datetimeutil"), + ("akkudoktoreos.optimization.alpha.alphasolution", "akkudoktoreos.core.emplan"), + ( + "akkudoktoreos.optimization.alpha.alphaconvert", + "akkudoktoreos.optimization.optimization:OptimizationSolution", + ), + # Outside code importing the optimizer's package. + ("akkudoktoreos.core.ems", "akkudoktoreos.optimization.alpha"), + ("akkudoktoreos.core.ems", "akkudoktoreos.optimization.alpha:AlphaOptimizer"), + # Pydantic where external input arrives. + ("akkudoktoreos.optimization.alpha.alpharequest", "pydantic"), + ("akkudoktoreos.optimization.alpha.alphasettings", "akkudoktoreos.core.pydantic"), + ("akkudoktoreos.optimization.alpha.alphaapi", "pydantic"), + ("akkudoktoreos.optimization.alpha.alphaprepare", "pydantic"), + # Pydantic outside optimizers. + ("akkudoktoreos.core.emplan", "pydantic"), + # Harmless names from core.coreabc. + ( + "akkudoktoreos.optimization.alpha.alpha", + "akkudoktoreos.core.coreabc:documentation_mode", + ), + # Third-party imports. + ("akkudoktoreos.devices.alpha.battery", "numpy"), + ], + ) + def test_allows(self, module: str, imported: str) -> None: + assert list(_check(module, imported, SYNTHETIC_OPTIMIZERS)) == [] + + def test_discovers_optimizers(self, tmp_path: Path) -> None: + """Packages under ``optimization/`` are optimizers, with ``devices/`` if present.""" + package = tmp_path / PACKAGE + _write(package / "optimization" / "optimization.py") + _write(package / "optimization" / "alpha" / "__init__.py") + _write(package / "optimization" / "beta" / "betaoptimizer.py") + (package / "optimization" / "empty").mkdir() + _write(package / "devices" / "alpha" / "battery.py") + assert _discover_optimizers(tmp_path) == { + "alpha": ("akkudoktoreos.optimization.alpha", "akkudoktoreos.devices.alpha"), + "beta": ("akkudoktoreos.optimization.beta",), + } + + def test_module_names_match_case_exactly( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """A name differing only in case is no module, as on Windows and macOS file systems.""" + _write(tmp_path / PACKAGE / "optimization" / "alpha" / "alphaoptimizer.py") + real_is_file, real_is_dir = Path.is_file, Path.is_dir + + def ignore_case(test: Callable[[Path], bool]) -> Callable[[Path], bool]: + def lookup(path: Path) -> bool: + if test(path): + return True + parent = path.parent + return real_is_dir(parent) and any( + entry.lower() == path.name.lower() and test(parent / entry) + for entry in os.listdir(parent) + ) + + return lookup + + monkeypatch.setattr(Path, "is_file", ignore_case(real_is_file)) + monkeypatch.setattr(Path, "is_dir", ignore_case(real_is_dir)) + assert (tmp_path / PACKAGE / "optimization" / "alpha" / "AlphaOptimizer.py").is_file() + assert _is_module(f"{PACKAGE}.optimization.alpha.alphaoptimizer", tmp_path) + assert not _is_module(f"{PACKAGE}.optimization.alpha.AlphaOptimizer", tmp_path) + assert not _is_module(f"{PACKAGE}.optimization.Alpha.alphaoptimizer", tmp_path) + + def test_recognises_preparation_package(self, tmp_path: Path) -> None: + """``prepare/`` counts as parameter preparation only as a package.""" + module = "akkudoktoreos.optimization.alpha.prepare" + assert not _is_preparation(module, "alpha", tmp_path) + _write(tmp_path / PACKAGE / "optimization" / "alpha" / "prepare" / "__init__.py") + assert _is_preparation(module, "alpha", tmp_path) + + def test_settings_imports_configabc_as_module(self, tmp_path: Path) -> None: + """``from akkudoktoreos.config import configabc`` depends on configabc only.""" + path = tmp_path / "alphasettings.py" + _write(path, "from akkudoktoreos.config import configabc\n") + module = "akkudoktoreos.optimization.alpha.alphasettings" + imported = list(_imports(path, module)) + assert "akkudoktoreos.config" not in imported + assert [v for i in imported for v in _check(module, i, SYNTHETIC_OPTIMIZERS)] == [] + + def test_resolves_relative_imports(self, tmp_path: Path) -> None: + """A relative import is checked like the absolute one it stands for.""" + path = tmp_path / "alphaconvert.py" + _write(path, "from ...config import config\n") + module = "akkudoktoreos.optimization.alpha.alphaconvert" + imported = list(_imports(path, module)) + assert "akkudoktoreos.config.config" in imported + violations = {v for i in imported for v in _check(module, i, SYNTHETIC_OPTIMIZERS)} + assert violations == {Violation("world-access", module, "akkudoktoreos.config.config")}