test(optimization): allow output-contract and request-schema names

Additional changes
- Describe contract names and roles in the skill, MIGRATION.md and ADRs 0004 and 0007.

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 8c06245e8b
commit b108335ee4
5 changed files with 169 additions and 35 deletions
@@ -52,8 +52,8 @@ with `--finalize`, and the architecture test passes with the fixed entries remov
## What may remain in `BASELINE` ## What may remain in `BASELINE`
After step 6 GENETIC0 kept three entries, all types of the output contract or the public request Nothing. After step 6 GENETIC0 has no entry left: the output-contract and public-schema types it
schema that live in banned modules: the solution's DataFrame (`core.pydantic`), the plan's needs from banned modules are contract names of the test (`CONTRACT_NAMES`, allowed in the roles
operation-mode enums (`devices.devicesabc`) and `TimeWindowSequence` (`config.configabc`). of `CONTRACT_ROLES`). An entry left after
Whether the test should allow these types is an open decision; until it is made they stay in the last step is unfinished migration; a further contract type is added to `CONTRACT_NAMES`, with
`BASELINE`, and any other entry left is unfinished migration. its reason in the pull request.
+9 -4
View File
@@ -25,14 +25,19 @@ and flag any conflict.
cache in `core.cache`). This includes data only needed to present the 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 solution: time zone, device IDs, run start and the prediction series the run
used travel in the optimization parameters. The modules and names this 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 `tests/test_optimizerarchitecture.py`; that list is authoritative. Among
them: `config`, `prediction`, `measurement`, `adapter`, `server`, them: `config`, `prediction`, `measurement`, `adapter`, `server`,
`core.ems`, `core.cache`, the `core.*settings` and database modules, the `core.ems`, `core.cache`, the `core.*settings` and database modules, the
`core.coreabc` mixins and getters, `OptimizationBase` and the shared device `core.coreabc` mixins and getters, `OptimizationBase` and the shared device
configuration (`devices.settings`, `devices.profile`, `devices.devices`, configuration (`devices.settings`, `devices.profile`, `devices.devices`,
`devices.devicesabc`). From `optimization.optimization` only the contract `devices.devicesabc`). From `optimization.optimization` only
class `OptimizationSolution` may be imported (`CONTRACT_NAMES`). `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 - 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. "Optimization parameters are always valid" rules of the `energy-domain` skill.
- Parameter preparation does not read EMS state either (`core.ems`, - Parameter preparation does not read EMS state either (`core.ems`,
@@ -155,7 +160,7 @@ classes `<Name><Role>`. 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 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. 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 - 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 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 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 types during parameter preparation; do not pass settings objects or enums from the
@@ -29,7 +29,11 @@ optimizer, not even its package.
- The output contract still lives in `optimization/optimization.py` together with - 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 `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 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 - 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 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.
@@ -24,10 +24,12 @@ The test holds the one authoritative list of these modules and names, including
the configuration, the server (`akkudoktoreos.server`, the configuration, the server (`akkudoktoreos.server`,
[0011](0011-optimizer-api-visualization-and-wizard-get-no-exception.md)), the shared device [0011](0011-optimizer-api-visualization-and-wizard-get-no-exception.md)), the shared device
configuration (`devices.settings`, `devices.profile`, `devices.devices`, `devices.devicesabc`) and 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 the contract names that may be imported from a module that mixes them with configuration or
(`optimization.optimization`). Parameter preparation is recognized by its file name, Pydantic (`optimization.optimization`, `core.pydantic`, `devices.devicesabc`, `config.configabc`):
`optimization/<name>/<name>prepare.py` or a subpackage `optimization/<name>/prepare/` (a plain the output contract and the public request schema, which every optimizer needs, allowed only in the
module `prepare.py` does not count); the settings modules that build the output or define the request. 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 model `optimization/<name>/<name>settings.py` may import `config.configabc` to define
`optimization.<name>`. The test discovers the optimizers (every package under `optimization/`), so `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 adding one does not touch it; until the simulation devices have moved into the optimizer
+143 -20
View File
@@ -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 - ``pydantic``: only the settings, request, preparation and API modules of an
optimizer import Pydantic; optimization parameters are dataclasses. 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 Violations that existed when the test was introduced are listed in
``BASELINE``. The baseline only shrinks: a violation missing from it fails, and ``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 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"}), "akkudoktoreos.utils.gridinterpolator": frozenset({"configured_grid_interpolator_backend"}),
} }
# Modules that mix the output contract with configuration: outside parameter # Modules that mix the output contract or the public request schema with
# preparation an optimizer imports only the listed contract names (ADR 0004). # 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]] = { CONTRACT_NAMES: dict[str, frozenset[str]] = {
"akkudoktoreos.optimization.optimization": frozenset({"OptimizationSolution"}), "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 # 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 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 ``b``, ``from a import *``) also yields ``module:*``: every name in it is
reachable. Function-level and ``TYPE_CHECKING`` imports count: they are 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)) tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
package = module if path.name == "__init__.py" else module.rsplit(".", 1)[0] 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 submodule
yield f"{submodule}:*" yield f"{submodule}:*"
else: else:
yield source if alias.name not in CONTRACT_NAMES.get(source, frozenset()):
yield source
yield f"{source}:{alias.name}" yield f"{source}:{alias.name}"
@@ -310,8 +331,25 @@ def _check(module: str, imported: str, optimizers: Optimizers) -> Iterator[Viola
yield Violation("preparation", module, source) yield Violation("preparation", module, source)
return return
if name: 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 ( 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) yield Violation("world-access", module, imported)
return return
@@ -456,11 +494,6 @@ BASELINE: frozenset[Violation] = frozenset(
"akkudoktoreos.optimization.genetic.terminalvalue", "akkudoktoreos.optimization.genetic.terminalvalue",
"pydantic", "pydantic",
), ),
Violation(
"pydantic",
"akkudoktoreos.optimization.genetic0.genetic0convert",
"akkudoktoreos.core.pydantic",
),
Violation( Violation(
"shared-config", "shared-config",
"akkudoktoreos.devices.settings.batterysettings", "akkudoktoreos.devices.settings.batterysettings",
@@ -596,16 +629,6 @@ BASELINE: frozenset[Violation] = frozenset(
"akkudoktoreos.optimization.genetic.geneticvisualize", "akkudoktoreos.optimization.genetic.geneticvisualize",
"akkudoktoreos.core.coreabc:get_ems", "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 assert "akkudoktoreos.config.config" in imported
violations = {v for i in imported for v in _check(module, i, SYNTHETIC_OPTIMIZERS)} violations = {v for i in imported for v in _check(module, i, SYNTHETIC_OPTIMIZERS)}
assert violations == {Violation("world-access", module, "akkudoktoreos.config.config")} 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}