From 8c06245e8b9f36b4bd539fb13209649ec6e7ca7f Mon Sep 17 00:00:00 2001 From: Bobby Noelte Date: Mon, 23 Nov 2026 20:23:26 +0000 Subject: [PATCH] docs(optimization): record the lessons of the GENETIC0 migration Additional changes - Correct a stale GENETIC0 docstring. - Count infinite readings and predictions as missing in the energy-domain rule. Co-Authored-By: Claude Opus 5.5 Assisted-by: Claude Code (claude-opus-5-5) --- GLOSSARY.md | 5 ++ ai/skills/energy-domain/SKILL.md | 1 + ai/skills/optimizer-architecture/MIGRATION.md | 59 +++++++++++++++++++ ai/skills/optimizer-architecture/SKILL.md | 42 +++++++++++-- ...-see-only-their-optimization-parameters.md | 4 ++ ...optimizer-interface-prepare-run-convert.md | 12 ++-- ...optimizer-refactoring-preserves-results.md | 14 ++++- ...optimization-parameters-are-dataclasses.md | 11 +++- ...ory-and-one-naming-scheme-per-optimizer.md | 5 +- ...sualization-and-wizard-get-no-exception.md | 6 +- .../genetic0/genetic0parameters.py | 5 +- 11 files changed, 145 insertions(+), 19 deletions(-) create mode 100644 ai/skills/optimizer-architecture/MIGRATION.md diff --git a/GLOSSARY.md b/GLOSSARY.md index 5507bc3d..f0020b9e 100644 --- a/GLOSSARY.md +++ b/GLOSSARY.md @@ -44,6 +44,11 @@ _Avoid_: start solution, previous solution The complete, valid input set handed to one optimizer for one optimization run. _Avoid_: optimization input, request parameters +**Presentation data**: +The part of the optimization parameters that only the solution conversion and the visualization +use, such as the time zone, device IDs, the run start and the prediction series the run used. +_Avoid_: display data, conversion context + **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. diff --git a/ai/skills/energy-domain/SKILL.md b/ai/skills/energy-domain/SKILL.md index 4c4f7f7a..71dd18d1 100644 --- a/ai/skills/energy-domain/SKILL.md +++ b/ai/skills/energy-domain/SKILL.md @@ -30,6 +30,7 @@ optimization run. This is a hard rule. - It covers the whole path from configuration, predictions and measurements to the parameters handed to an optimizer, for every optimizer (GENETIC, GENETIC0 and future ones), including device and operating-point parameters. +- A NaN or infinite reading or prediction value the run reads counts as missing. - Replace an invalid or missing input with a **fallback value**: 1. the configuration field's default, 2. a heuristic only when there is no default or the default does not fit diff --git a/ai/skills/optimizer-architecture/MIGRATION.md b/ai/skills/optimizer-architecture/MIGRATION.md new file mode 100644 index 00000000..12b87b0c --- /dev/null +++ b/ai/skills/optimizer-architecture/MIGRATION.md @@ -0,0 +1,59 @@ +# Migrating an optimizer to the architecture + +The path GENETIC0 took (ADR 0008), for GENETIC and any later optimizer. One pull request per +step; every step proves its results identical with the golden tests and removes the `BASELINE` +entries it fixes. + +## Steps + +0. **Safety net.** Characterization tests that pin the whole output per golden input: raw + result, optimization solution, energy management plan and visualization. No production code. +1. **Interface and registry.** An adapter `Optimizer` wraps the existing code; the energy + management drives the optimizer only through the registry and keeps its run in the generic + slot. +2. **Layout.** Move into `optimization//` and rename to the role names. Relabel the moved + modules' `BASELINE` entries one to one. +3. **Preparation and parameters.** `prepare.py` and the parameters dataclass with the run + settings and presentation data; `run()` reads only the parameters. Replay files arrive here. +4. **Simulation devices** as frozen dataclasses derived from the request. +5. **Conversion and visualization** from the parameters and the result only. +6. **Result and API.** The result dataclass, `api.py` with the response models and + `api()`; the server no longer imports the optimizer. + +The step is done when its golden and replay tests pass unchanged, the long golden case passes +with `--finalize`, and the architecture test passes with the fixed entries removed. + +## Characterization tests + +- Fix the run start (a date and hour, plus one case across a DST switch) instead of today. +- Mask wall-clock values (solution `id`, `generated_at`, the UUID part of instruction IDs). +- Feed the conversion from a fake prediction whose values follow the absolute time and encode + the fill method, so a shifted window or a swapped fill method changes the pinned output. When + the prediction series move into the parameters, patch the same fake into the parameter + preparation; the golden output stays the same. +- Pin the visualization by spying on the arguments of the report's chart methods, not the PDF + text (it holds `now()`). Later steps keep those method names and signatures. +- Run each case twice in separate processes before committing the goldens. +- Compare Pydantic models by `model_dump()` or their JSON, not `==`. + +## Move, then fix + +- Rule breaches whose fix changes results (a preparation that writes the configuration, invents + demo devices or cancels the run) move unchanged in the structural step. The fix is the next, + separately declared behaviour-change pull request. +- Known bugs of the old output stay reproduced (GENETIC0: EV and home appliance IDs always + `ev1` / `homeappliance1`). Report them; for GENETIC0, fix them in GENETIC if it has the same + code. +- A structural step that changes behaviour outside the results (GENETIC0 step 1: a raising + preparation now cancels the run, `POST /optimize` answers 404 instead of 500) declares it in + its pull request under **Merge Danger**; the golden results still stay the same. +- A step may keep a transitional seam (e.g. an optional argument the conversion falls back from) + only when the plan names the step that removes it. + +## What may remain in `BASELINE` + +After step 6 GENETIC0 kept three entries, all types of the output contract or the public request +schema that live in banned modules: the solution's DataFrame (`core.pydantic`), the plan's +operation-mode enums (`devices.devicesabc`) and `TimeWindowSequence` (`config.configabc`). +Whether the test should allow these types is an open decision; until it is made they stay in +`BASELINE`, and any other entry left is unfinished migration. diff --git a/ai/skills/optimizer-architecture/SKILL.md b/ai/skills/optimizer-architecture/SKILL.md index 15906ac3..8a68049e 100644 --- a/ai/skills/optimizer-architecture/SKILL.md +++ b/ai/skills/optimizer-architecture/SKILL.md @@ -6,8 +6,9 @@ description: Use when creating, changing, refactoring or removing an optimizer ( # 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. +parameters**, **presentation data**, **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 @@ -90,8 +91,23 @@ moment of the run that measurements (e.g. a measured state of charge) refer to. 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. +- **Presentation data cover every entry point.** A client's request may start in another time + zone than the configured one or carry longer arrays than an automatic run; prepare the series + for the widest window the conversion can need, and let `convert()` take its own share. + Building them follows the fallback rules too: a series that cannot be read is left out with + an error log. +- Derive the simulation's device dataclasses from the request with pure functions + (`Request.to_parameters()`): no configuration, no clock (a date comes from the + run start in the parameters), no change to the request. A replay file can then store the + request and derive them again. GENETIC0's home appliance breaks this (today's date, writes a + default time window into the request); it is frozen, so do not copy it. - 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. + from a stored parameter file, under a deliberately different configuration, when you change + what goes into the parameters, and one that asserts the replay (de)serialization round trip is + lossless. +- The result (`R`) is a frozen dataclass. Where `api.py` builds public response models + from it, normalise its values as those models validate them (NumPy arrays to lists, NaN to + `None`, the fields' number types), so the responses stay identical. ## Layout and names (ADR 0010) @@ -116,8 +132,18 @@ classes ``. This table is the one maintained copy; ADR 0010 links he - A new module that fits no role still gets the `` prefix. Do not invent a second name for an existing role. +- Nested request models are `Request`; `Parameters` + names the simulation's device dataclass. +- Renaming a Pydantic model changes its schema name in OpenAPI and the + configuration documentation, and moving a route into an optimizer's router + changes the OpenAPI paths: regenerate the docs and declare it as + **Breaking:** in the pull request. - Dataclasses are `@dataclass(frozen=True, slots=True)`. A run never changes - its inputs. + its inputs; parameters hold sequences as tuples. +- The parameters may keep the Pydantic optimization request they were derived + from (GENETIC0 does, for replay files, conversion, visualization and API), + an exception to the tuple rule; the algorithm and the simulation read the + derived dataclasses, never the request. - Only `settings.py`, `request.py`, parameter preparation and `api.py` may import `pydantic` or `akkudoktoreos.core.pydantic`. @@ -215,5 +241,9 @@ against `BASELINE`, the violations that existed when it was introduced. 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. +- Before refactoring an optimizer, pin its whole output per golden input + (solution, plan, visualization); add replay files (complete optimization + parameters plus the expected result) as soon as the parameter type exists. +- **Migrating an optimizer** to this architecture: follow the steps, + characterization technique and move-then-fix rule in `MIGRATION.md` next to + this file. diff --git a/docs/adr/0003-optimizers-see-only-their-optimization-parameters.md b/docs/adr/0003-optimizers-see-only-their-optimization-parameters.md index dae68893..6d0b835e 100644 --- a/docs/adr/0003-optimizers-see-only-their-optimization-parameters.md +++ b/docs/adr/0003-optimizers-see-only-their-optimization-parameters.md @@ -24,3 +24,7 @@ run and the prediction series the run was optimized against. - 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). +- The presentation data cover every entry point, not only the automatic run. A client's + optimization request may start in another time zone than the configured one or carry longer + arrays, so the prepared series span the widest window the conversion can need, and the + conversion takes its own share of them (GENETIC0 migration). diff --git a/docs/adr/0006-optimizer-interface-prepare-run-convert.md b/docs/adr/0006-optimizer-interface-prepare-run-convert.md index ec2e5541..6cb656fd 100644 --- a/docs/adr/0006-optimizer-interface-prepare-run-convert.md +++ b/docs/adr/0006-optimizer-interface-prepare-run-convert.md @@ -1,13 +1,15 @@ # Optimizers implement prepare, run and convert -Every optimizer follows the same three-step interface, so the energy management can drive any of +Every optimizer follows the same three-step interface (prepare, run, convert), 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, the observation time, the warm start and run-time overrides), `run()` and `convert()` -(asynchronous), 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`). +start, the observation time, the warm start and run-time overrides), `run()`, `convert()` +(asynchronous), which returns the optimization solution and the energy management plan, and +`api()`, which hands out the optimizer's REST router +([0011](0011-optimizer-api-visualization-and-wizard-get-no-exception.md)). 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. diff --git a/docs/adr/0008-optimizer-refactoring-preserves-results.md b/docs/adr/0008-optimizer-refactoring-preserves-results.md index a00182a3..fa137a74 100644 --- a/docs/adr/0008-optimizer-refactoring-preserves-results.md +++ b/docs/adr/0008-optimizer-refactoring-preserves-results.md @@ -14,10 +14,18 @@ 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. +- Before an optimizer is refactored, characterization tests pin its whole output per golden + input: the optimization solution, the energy management plan and the visualization, not only + the raw result. The raw result alone missed most of what the GENETIC0 migration moved. +- Replay files (complete optimization parameters in the new parameter type plus the expected + result) are added as soon as the optimizer has its parameter type, in the same pull request. +- Code that breaks an architecture rule in a way whose fix changes results (e.g. a parameter + preparation that writes the configuration or cancels the run) is first moved unchanged; the fix + follows in its own declared behaviour-change pull request. +- A refactoring reproduces known bugs of the old output too (GENETIC0 always reports the EV and + home appliance IDs `ev1` and `homeappliance1`); they are reported, not fixed on the way. - GENETIC0 is migrated first, as the pilot; the registry and the interface arrive with its first - migration pull request. GENETIC follows. + migration pull request. GENETIC follows on the same path. - A GENETIC0 bug that matters to users is fixed in GENETIC (or a new optimizer), not in GENETIC0. - One declared exception: GENETIC0's parameter preparation follows the "optimization parameters are always valid" rule of the `energy-domain` skill, in a behaviour-change pull request of its diff --git a/docs/adr/0009-optimization-parameters-are-dataclasses.md b/docs/adr/0009-optimization-parameters-are-dataclasses.md index 320a1ddf..036efc75 100644 --- a/docs/adr/0009-optimization-parameters-are-dataclasses.md +++ b/docs/adr/0009-optimization-parameters-are-dataclasses.md @@ -20,4 +20,13 @@ requests are Pydantic models, and the settings models of the configuration stay - 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. +- Replay files need an explicit (de)serialization of the dataclasses instead of Pydantic's; a + test asserts that the round trip is lossless. +- The simulation's device parameters are derived from the optimization request by pure functions + (no configuration, no clock, no change to the request), so a replay file may store the request + and derive them again. GENETIC0's home appliance still reads today's date there and writes a + default time window into the request; it is frozen. +- The optimization result is a frozen dataclass as well. Where public response models are built + from it, its values are normalised as those models validate them (NumPy arrays to lists, NaN to + `None`, the fields' number types), so the responses do not change when the result stops being + a Pydantic model. 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 index 5d19ce9f..b553ab61 100644 --- 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 @@ -20,7 +20,10 @@ fit a role use the `` prefix as well, also inside subdirectories such as ` - 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. + schema names in OpenAPI and the configuration documentation change. Nested request models are + renamed `Request` as well (e.g. `Genetic0InverterParameters` → + `Genetic0InverterRequest`); the name `Parameters` belongs to the simulation's + device dataclasses. - `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 index 748561e1..d8cf0988 100644 --- 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 @@ -13,7 +13,11 @@ state today. None of them gets an exception from 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. + imports the server either. It reports errors as the generic `OptimizerProblem`, which the server + renders like its own problem responses, and it holds the public response models, built from the + optimization parameters and result. The server includes the optimizers' routers before its own + routes, so an optimizer's specific path (`.../solution/GENETIC0`) wins over a generic one + (`.../solution/{algorithm}`). - 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. diff --git a/src/akkudoktoreos/optimization/genetic0/genetic0parameters.py b/src/akkudoktoreos/optimization/genetic0/genetic0parameters.py index c3041195..d2360c8e 100644 --- a/src/akkudoktoreos/optimization/genetic0/genetic0parameters.py +++ b/src/akkudoktoreos/optimization/genetic0/genetic0parameters.py @@ -5,8 +5,9 @@ parameters, and the data the solution conversion presents (time zone, device IDs series). They are prepared once before the run by ``genetic0prepare``. The simulation reads the forecast and device dataclasses, which are derived from the request -(``Genetic0Request``). The request itself is kept because the result echoes it (until step 5); a -replay file stores the request and the dataclasses are derived again when it is read. +(``Genetic0Request``). The request itself is kept for the conversion, the visualization and the +public responses; a replay file stores the request and the dataclasses are derived again when it +is read. """ import math