diff --git a/ai/skills/optimizer-architecture/MIGRATION.md b/ai/skills/optimizer-architecture/MIGRATION.md index 12b87b0c..40cbc8e7 100644 --- a/ai/skills/optimizer-architecture/MIGRATION.md +++ b/ai/skills/optimizer-architecture/MIGRATION.md @@ -52,8 +52,8 @@ with `--finalize`, and the architecture test passes with the fixed entries remov ## 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. +Nothing. After step 6 GENETIC0 has no entry left: the output-contract and public-schema types it +needs from banned modules are contract names of the test (`CONTRACT_NAMES`, allowed in the roles +of `CONTRACT_ROLES`). An entry left after +the last step is unfinished migration; a further contract type is added to `CONTRACT_NAMES`, with +its reason in the pull request. diff --git a/ai/skills/optimizer-architecture/SKILL.md b/ai/skills/optimizer-architecture/SKILL.md index 8a68049e..8d391042 100644 --- a/ai/skills/optimizer-architecture/SKILL.md +++ b/ai/skills/optimizer-architecture/SKILL.md @@ -25,14 +25,19 @@ and flag any conflict. 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 + covers are listed once, in `WORLD_MODULES`, `WORLD_NAMES` and `PREPARATION_BANNED_*` 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`). + `devices.devicesabc`). From `optimization.optimization` only + `OptimizationSolution` may be imported. The other contract names of + `CONTRACT_NAMES` (`PydanticDateTimeDataFrame` of the solution, the plan's + `BatteryOperationMode` and `ApplianceOperationMode`, the request schema's + `TimeWindow` and `TimeWindowSequence`) are allowed only in the request, + conversion, visualization and API modules (`CONTRACT_ROLES`), never in the + parameters or the simulation. - 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`, @@ -155,7 +160,7 @@ classes ``. This table is the one maintained copy; ADR 0010 links he 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 + output contract (`OptimizationSolution`, the energy management plan, and in the roles above the contract names) 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 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 index 4ce6ebdc..d541a8a9 100644 --- a/docs/adr/0004-optimizers-duplicate-code-instead-of-sharing-it.md +++ b/docs/adr/0004-optimizers-duplicate-code-instead-of-sharing-it.md @@ -29,7 +29,11 @@ optimizer, not even its package. - 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. + preparation; the architecture test lists them. The same holds for the contract types that live + in otherwise banned modules: the solution's `PydanticDateTimeDataFrame`, the operation-mode enums + the plan's instructions name and the request schema's time windows (`TimeWindow`, + `TimeWindowSequence`), but only in the modules that build the output or define the request; the + parameters and the simulation never see 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. + parameter preparation, and uses the enums again only to name operation modes in its output. diff --git a/docs/adr/0007-architecture-test-with-shrinking-baseline.md b/docs/adr/0007-architecture-test-with-shrinking-baseline.md index 6a6f7a12..08b47bc0 100644 --- a/docs/adr/0007-architecture-test-with-shrinking-baseline.md +++ b/docs/adr/0007-architecture-test-with-shrinking-baseline.md @@ -24,10 +24,12 @@ The test holds the one authoritative list of these modules and names, including 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 +the contract names that may be imported from a module that mixes them with configuration or +Pydantic (`optimization.optimization`, `core.pydantic`, `devices.devicesabc`, `config.configabc`): +the output contract and the public request schema, which every optimizer needs, allowed only in the +modules that build the output or define the request. 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 diff --git a/tests/test_optimizerarchitecture.py b/tests/test_optimizerarchitecture.py index 616a8295..89d65311 100644 --- a/tests/test_optimizerarchitecture.py +++ b/tests/test_optimizerarchitecture.py @@ -23,6 +23,10 @@ Parses the imports of ``src/akkudoktoreos`` and checks these rules: - ``pydantic``: only the settings, request, preparation and API modules of an optimizer import Pydantic; optimization parameters are dataclasses. +The output contract and the public request schema partly live in modules these +rules ban; from them the roles in ``CONTRACT_ROLES`` may import the names in +``CONTRACT_NAMES``. + 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 @@ -142,10 +146,25 @@ WORLD_NAMES: dict[str, frozenset[str]] = { "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). +# Modules that mix the output contract or the public request schema with +# configuration or Pydantic: from them an optimizer imports only the listed +# names (ADR 0004, 0007): the solution, its DataFrame type, the operation-mode +# enums of the plan's instructions and the time windows of a request. CONTRACT_NAMES: dict[str, frozenset[str]] = { "akkudoktoreos.optimization.optimization": frozenset({"OptimizationSolution"}), + "akkudoktoreos.core.pydantic": frozenset({"PydanticDateTimeDataFrame"}), + "akkudoktoreos.devices.devicesabc": frozenset( + {"ApplianceOperationMode", "BatteryOperationMode"} + ), + "akkudoktoreos.config.configabc": frozenset({"TimeWindow", "TimeWindowSequence"}), +} +# The roles that build the output or define the public schema, the only ones +# that may import the contract names of these modules; the parameters and the +# simulation stay free of Pydantic and configuration types (ADR 0009, 0004). +CONTRACT_ROLES: dict[str, tuple[str, ...]] = { + "akkudoktoreos.core.pydantic": ("request", "convert", "visualize", "api"), + "akkudoktoreos.devices.devicesabc": ("request", "convert", "visualize", "api"), + "akkudoktoreos.config.configabc": ("request", "convert", "visualize", "api"), } # EMS state and the server, banned in parameter preparation too: the energy @@ -236,7 +255,8 @@ def _imports(path: Path, module: str) -> Iterator[str]: 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. + dependencies as well. A name listed in ``CONTRACT_NAMES`` yields only + ``module:name``: importing it is no dependency on the rest of the module. """ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) package = module if path.name == "__init__.py" else module.rsplit(".", 1)[0] @@ -259,7 +279,8 @@ def _imports(path: Path, module: str) -> Iterator[str]: yield submodule yield f"{submodule}:*" else: - yield source + if alias.name not in CONTRACT_NAMES.get(source, frozenset()): + yield source yield f"{source}:{alias.name}" @@ -310,8 +331,25 @@ def _check(module: str, imported: str, optimizers: Optimizers) -> Iterator[Viola yield Violation("preparation", module, source) return if name: + # A module listed in WORLD_MODULES or PYDANTIC_MODULES is reported by + # its bare import, which _imports() yields for every non-contract name; + # a contract name outside CONTRACT_ROLES gets the same label. + if ( + source in CONTRACT_ROLES + and name in CONTRACT_NAMES[source] + and not any(_has_role(module, own, role) for role in CONTRACT_ROLES[source]) + and not ( + _has_role(module, own, "settings") + and _within_any(source, SETTINGS_ALLOWED_MODULES + PYDANTIC_MODULES) + ) + ): + rule = "pydantic" if _within_any(source, PYDANTIC_MODULES) else "world-access" + yield Violation(rule, module, source) + return if _names_hit(WORLD_NAMES, source, name) or ( - source in CONTRACT_NAMES and name not in CONTRACT_NAMES[source] + source in CONTRACT_NAMES + and name not in CONTRACT_NAMES[source] + and not _within_any(source, WORLD_MODULES + PYDANTIC_MODULES) ): yield Violation("world-access", module, imported) return @@ -456,11 +494,6 @@ BASELINE: frozenset[Violation] = frozenset( "akkudoktoreos.optimization.genetic.terminalvalue", "pydantic", ), - Violation( - "pydantic", - "akkudoktoreos.optimization.genetic0.genetic0convert", - "akkudoktoreos.core.pydantic", - ), Violation( "shared-config", "akkudoktoreos.devices.settings.batterysettings", @@ -596,16 +629,6 @@ BASELINE: frozenset[Violation] = frozenset( "akkudoktoreos.optimization.genetic.geneticvisualize", "akkudoktoreos.core.coreabc:get_ems", ), - Violation( - "world-access", - "akkudoktoreos.optimization.genetic0.genetic0convert", - "akkudoktoreos.devices.devicesabc", - ), - Violation( - "world-access", - "akkudoktoreos.optimization.genetic0.genetic0request", - "akkudoktoreos.config.configabc", - ), } ) @@ -934,3 +957,103 @@ class TestOptimizerArchitecture: 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")} + + @pytest.mark.parametrize( + "source", + [ + "from akkudoktoreos.core.pydantic import PydanticDateTimeDataFrame\n", + "from akkudoktoreos.devices.devicesabc import ApplianceOperationMode, " + "BatteryOperationMode\n", + "from akkudoktoreos.config.configabc import TimeWindow, TimeWindowSequence\n", + "from akkudoktoreos.optimization.optimization import OptimizationSolution\n", + ], + ) + def test_allows_contract_names(self, tmp_path: Path, source: str) -> None: + """Contract names may be imported from modules that are otherwise banned.""" + path = tmp_path / "alphaconvert.py" + _write(path, source) + module = "akkudoktoreos.optimization.alpha.alphaconvert" + imported = list(_imports(path, module)) + assert [v for i in imported for v in _check(module, i, SYNTHETIC_OPTIMIZERS)] == [] + + @pytest.mark.parametrize( + ("module", "source", "rule"), + [ + ( + "akkudoktoreos.optimization.alpha.alphaparameters", + "from akkudoktoreos.config.configabc import TimeWindowSequence\n", + "world-access", + ), + ( + "akkudoktoreos.optimization.alpha.devices.alphabattery", + "from akkudoktoreos.devices.devicesabc import BatteryOperationMode\n", + "world-access", + ), + ( + "akkudoktoreos.optimization.alpha.alphasimulation", + "from akkudoktoreos.core.pydantic import PydanticDateTimeDataFrame\n", + "pydantic", + ), + ( + "akkudoktoreos.optimization.alpha.alphaconvert", + "from akkudoktoreos.config.configabc import *\n", + "world-access", + ), + ( + "akkudoktoreos.optimization.alpha.alphaconvert", + "import akkudoktoreos.devices.devicesabc as modes\n", + "world-access", + ), + ], + ) + def test_contract_names_only_in_contract_roles( + self, tmp_path: Path, module: str, source: str, rule: str + ) -> None: + """Parameters and simulation import no contract names; whole modules stay banned.""" + path = tmp_path / "module.py" + _write(path, source) + imported = list(_imports(path, module)) + violations = {v for i in imported for v in _check(module, i, SYNTHETIC_OPTIMIZERS)} + assert {v.rule for v in violations} == {rule} + + @pytest.mark.parametrize( + ("source", "expected"), + [ + ( + "from akkudoktoreos.core.pydantic import PydanticBaseModel, " + "PydanticDateTimeDataFrame\n", + Violation( + "pydantic", + "akkudoktoreos.optimization.alpha.alphaconvert", + "akkudoktoreos.core.pydantic", + ), + ), + ( + "from akkudoktoreos.devices.devicesabc import BatteryOperationMode, " + "ConsumerScheduleMode\n", + Violation( + "world-access", + "akkudoktoreos.optimization.alpha.alphaconvert", + "akkudoktoreos.devices.devicesabc", + ), + ), + ( + "import akkudoktoreos.config.configabc\n", + Violation( + "world-access", + "akkudoktoreos.optimization.alpha.alphaconvert", + "akkudoktoreos.config.configabc", + ), + ), + ], + ) + def test_detects_names_beside_contract_names( + self, tmp_path: Path, source: str, expected: Violation + ) -> None: + """Any other name, or the whole module, from such a module is a violation.""" + path = tmp_path / "alphaconvert.py" + _write(path, source) + module = "akkudoktoreos.optimization.alpha.alphaconvert" + imported = list(_imports(path, module)) + violations = {v for i in imported for v in _check(module, i, SYNTHETIC_OPTIMIZERS)} + assert violations == {expected}