mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-11-25 23:16:18 +01:00
fix: unify mypy environments for local checks and CI (#1291)
The isolated pre-commit mypy hook previously omitted runtime type information that make mypy used, hiding errors involving dependencies such as Pydantic and Pendulum. Makefile, pre-commit and CI now run the same full-project typing policy in the development environment defined by uv.lock. - Use uv run --locked --exact --extra dev and the same mypy arguments for Makefile and the local hook. Check all of src and tests, including on configuration-only changes. - Pin Python 3.13 for local development and the pre-commit CI job, and install the locked pre-commit version in CI. - Disable incremental analysis because existing Pendulum cache state changes mypy 2.3.1 diagnostics. Document the policy, the performance tradeoff and the existing typing debt. - Add a regression test that exercises Makefile, the hook and the CI command in a temporary project, accepting valid dependency types and detecting deliberate Pydantic/Pendulum assignment errors. Resolve the newly detected mypy diagnostics. - Enable the numpydantic and Pydantic mypy plugins, retaining strict Pydantic constructor typing with init_typed = true. Validate raw/coercible payloads through model_validate. - Propagate concrete record, provider and time-window types through generic collections, factories and lookup methods. Preserve runtime field inspection and generated time-window documentation. - Align Pendulum annotations with actual factory/arithmetic results while retaining Pydantic validation adapters at runtime. Correct optional values, array boundaries, REST handlers and plotting interfaces. - Add pinned scipy-stubs and types-psutil, update uv.lock, and supply the plugins' dependencies. - Add runtime regression coverage for validated path defaults, normalized time-series metadata, generic field inspection, invalid timestamps and unsupported provider imports. Runtime and compatibility details: - Validate path defaults as Path objects while retaining raw string defaults needed by migration serialization with exclude_defaults. - Normalize feed-in tariff lists and default charge rates to NumPy arrays; reject missing timestamps/uninitialized values explicitly. Importing into a provider without import support returns HTTP 400. - Public JSON schemas and OpenAPI structure match main (excluding the generated version). Signed-off-by: dr-dimitry Signed-off-by: dr-dimitry Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com> Co-authored-by: dr-dimitri <87113560+dr-dimitri@users.noreply.github.com> Co-authored-by: Normann <github@koldrack.com>
This commit is contained in:
co-authored by
dr-dimitri
Normann
parent
5b584cbb57
commit
1abdd345c4
@@ -14,7 +14,7 @@ import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any, ClassVar, Optional, Type, Union
|
||||
from typing import Any, Callable, ClassVar, Optional, Type, Union
|
||||
|
||||
import pydantic_settings
|
||||
from loguru import logger
|
||||
@@ -122,6 +122,10 @@ def default_data_folder_path() -> Path:
|
||||
class GeneralSettings(SettingsBaseModel):
|
||||
"""General settings."""
|
||||
|
||||
# Legacy configuration-path metadata populated by ConfigEOS._setup_config_file.
|
||||
_config_file_path: ClassVar[Path | None] = None
|
||||
_config_folder_path: ClassVar[Path | None] = None
|
||||
|
||||
config_save_mode: ConfigSaveMode = Field(
|
||||
default=ConfigSaveMode.AUTOMATIC,
|
||||
json_schema_extra={
|
||||
@@ -161,8 +165,11 @@ class GeneralSettings(SettingsBaseModel):
|
||||
},
|
||||
)
|
||||
|
||||
# Validate this raw default to Path. Retain the string so
|
||||
# exclude_defaults preserves the output path in migrated configurations.
|
||||
data_output_subpath: Optional[Path] = Field(
|
||||
default="output",
|
||||
validate_default=True,
|
||||
json_schema_extra={"description": "Sub-path for the EOS output data folder."},
|
||||
)
|
||||
|
||||
@@ -402,14 +409,15 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def settings_customise_sources(
|
||||
# Pydantic Settings accepts zero-argument callables as well as source objects.
|
||||
def settings_customise_sources( # type: ignore[override]
|
||||
cls,
|
||||
settings_cls: Type[pydantic_settings.BaseSettings],
|
||||
init_settings: pydantic_settings.PydanticBaseSettingsSource,
|
||||
env_settings: pydantic_settings.PydanticBaseSettingsSource,
|
||||
dotenv_settings: pydantic_settings.PydanticBaseSettingsSource,
|
||||
file_secret_settings: pydantic_settings.PydanticBaseSettingsSource,
|
||||
) -> tuple[pydantic_settings.PydanticBaseSettingsSource, ...]:
|
||||
) -> tuple[pydantic_settings.PydanticBaseSettingsSource | Callable[[], dict[str, Any]], ...]:
|
||||
"""Customizes the order and handling of settings sources for a pydantic_settings.BaseSettings subclass.
|
||||
|
||||
This method determines the sources for application configuration settings, including
|
||||
@@ -790,7 +798,11 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
|
||||
required by ``self._setup()``.
|
||||
OSError: If reading the backup file fails due to I/O issues.
|
||||
"""
|
||||
backup_file_path = self.general.config_file_path.with_suffix(f".{backup_id}")
|
||||
config_file_path = self.general.config_file_path
|
||||
# Configuration setup initializes this path; should never raise.
|
||||
if config_file_path is None:
|
||||
raise AssertionError("Configuration file path is not initialized")
|
||||
backup_file_path = config_file_path.with_suffix(f".{backup_id}")
|
||||
if not backup_file_path.exists():
|
||||
error_msg = f"Configuration backup `{backup_id}` not found."
|
||||
logger.error(error_msg)
|
||||
@@ -823,7 +835,10 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
|
||||
"""
|
||||
result: dict[str, dict[str, Any]] = {}
|
||||
|
||||
base_path: Path = self.general.config_file_path
|
||||
base_path = self.general.config_file_path
|
||||
# Configuration setup initializes this path; should never raise.
|
||||
if base_path is None:
|
||||
raise AssertionError("Configuration file path is not initialized")
|
||||
parent = base_path.parent
|
||||
stem = base_path.stem
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import calendar
|
||||
import os
|
||||
import sys
|
||||
from enum import StrEnum
|
||||
from typing import Any, ClassVar, Iterator, Optional, Union
|
||||
from typing import Any, ClassVar, Generic, Iterator, Optional, TypeVar, Union
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
@@ -409,19 +409,23 @@ class TimeWindow(SettingsBaseModel):
|
||||
return self.duration
|
||||
|
||||
|
||||
class TimeWindowSequence(SettingsBaseModel):
|
||||
TimeWindowT = TypeVar("TimeWindowT", bound=TimeWindow)
|
||||
|
||||
|
||||
class TimeWindowSequence(SettingsBaseModel, Generic[TimeWindowT]):
|
||||
"""Model representing a sequence of time windows with collective operations.
|
||||
|
||||
Manages multiple TimeWindow objects and provides methods to work with them
|
||||
as a cohesive unit for scheduling and availability checking.
|
||||
"""
|
||||
|
||||
windows: list[TimeWindow] = Field(
|
||||
windows: list[TimeWindowT] = Field(
|
||||
default_factory=list,
|
||||
json_schema_extra={"description": "List of TimeWindow objects that make up this sequence."},
|
||||
)
|
||||
|
||||
def __iter__(self) -> Iterator[TimeWindow]:
|
||||
# EOS collections iterate over their elements instead of BaseModel field/value pairs.
|
||||
def __iter__(self) -> Iterator[TimeWindowT]: # type: ignore[override]
|
||||
"""Allow iteration over the time windows."""
|
||||
return iter(self.windows)
|
||||
|
||||
@@ -429,7 +433,7 @@ class TimeWindowSequence(SettingsBaseModel):
|
||||
"""Return the number of time windows in the sequence."""
|
||||
return len(self.windows)
|
||||
|
||||
def __getitem__(self, index: int) -> TimeWindow:
|
||||
def __getitem__(self, index: int) -> TimeWindowT:
|
||||
"""Allow indexing into the time windows."""
|
||||
return self.windows[index]
|
||||
|
||||
@@ -536,7 +540,9 @@ class TimeWindowSequence(SettingsBaseModel):
|
||||
total += d
|
||||
return total
|
||||
|
||||
def get_applicable_windows(self, reference_date: Optional[DateTime] = None) -> list[TimeWindow]:
|
||||
def get_applicable_windows(
|
||||
self, reference_date: Optional[DateTime] = None
|
||||
) -> list[TimeWindowT]:
|
||||
"""Get all windows that apply to the given reference date.
|
||||
|
||||
Args:
|
||||
@@ -556,7 +562,7 @@ class TimeWindowSequence(SettingsBaseModel):
|
||||
|
||||
def find_windows_for_duration(
|
||||
self, duration: Duration, reference_date: Optional[DateTime] = None
|
||||
) -> list[TimeWindow]:
|
||||
) -> list[TimeWindowT]:
|
||||
"""Find all windows that can accommodate the given duration.
|
||||
|
||||
Args:
|
||||
@@ -575,7 +581,7 @@ class TimeWindowSequence(SettingsBaseModel):
|
||||
|
||||
def get_all_possible_start_times(
|
||||
self, duration: Duration, reference_date: Optional[DateTime] = None
|
||||
) -> list[tuple[DateTime, DateTime, TimeWindow]]:
|
||||
) -> list[tuple[DateTime, DateTime, TimeWindowT]]:
|
||||
"""Get all possible start time ranges for a duration across all windows.
|
||||
|
||||
Args:
|
||||
@@ -739,7 +745,7 @@ class TimeWindowSequence(SettingsBaseModel):
|
||||
dtype=np.float64,
|
||||
)
|
||||
|
||||
def add_window(self, window: TimeWindow) -> None:
|
||||
def add_window(self, window: TimeWindowT) -> None:
|
||||
"""Add a new time window to the sequence.
|
||||
|
||||
Args:
|
||||
@@ -747,7 +753,7 @@ class TimeWindowSequence(SettingsBaseModel):
|
||||
"""
|
||||
self.windows.append(window)
|
||||
|
||||
def remove_window(self, index: int) -> TimeWindow:
|
||||
def remove_window(self, index: int) -> TimeWindowT:
|
||||
"""Remove a time window from the sequence by index.
|
||||
|
||||
Args:
|
||||
@@ -781,7 +787,7 @@ class TimeWindowSequence(SettingsBaseModel):
|
||||
if reference_date is None:
|
||||
reference_date = pendulum.today()
|
||||
|
||||
def sort_key(window: TimeWindow) -> tuple[int, DateTime]:
|
||||
def sort_key(window: TimeWindowT) -> tuple[int, DateTime]:
|
||||
start_time = window.earliest_start_time(Duration(), reference_date)
|
||||
if start_time is None:
|
||||
return (1, reference_date)
|
||||
@@ -806,7 +812,7 @@ class ValueTimeWindow(TimeWindow):
|
||||
)
|
||||
|
||||
|
||||
class ValueTimeWindowSequence(TimeWindowSequence):
|
||||
class ValueTimeWindowSequence(TimeWindowSequence[ValueTimeWindow]):
|
||||
"""Sequence of value time windows.
|
||||
|
||||
This model specializes `TimeWindowSequence` to ensure that all
|
||||
|
||||
Reference in New Issue
Block a user