docs(optimization): add optimizer architecture ADRs, skill and test (#1572)

Additional changes
- Add the optimizer terms to the glossary.
- Point to the skill from AGENTS.md, docs/develop/ai.md and the energy-domain skill.
- Match module names case-exactly, also on case-insensitive file systems.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
Bobby Noelte
2026-11-27 13:55:41 +01:00
co-authored by Claude Opus 5.5
parent 1159501713
commit 9adf7b8be2
15 changed files with 1640 additions and 0 deletions
@@ -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).
@@ -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.
@@ -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/<name>/`
([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.<name>`) 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.<name>`
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.
@@ -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.
@@ -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 `<name>optimizer.py`, its package `__init__.py` and the
parameter preparation itself imports the parameter preparation, the optimizer's own package or
`<name>optimizer.py` (both may re-export it; only the package imports `<name>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/<name>/<name>prepare.py` or a subpackage `optimization/<name>/prepare/` (a plain
module `prepare.py` does not count); the settings
model `optimization/<name>/<name>settings.py` may import `config.configabc` to define
`optimization.<name>`. 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/<name>` 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.
@@ -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/<optimizer>/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.
@@ -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.
@@ -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/<name>/`, 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 `<name><role>.py` and every class
`<Name><Role>`, 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 `<name>` 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.
@@ -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 (`<name>visualize.py`) is part of the solution conversion and renders from the
optimization parameters and the optimization result only.
- The REST router (`<name>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 `<name>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.