fix(config): never autosave defaults over an unreadable config file

Additional changes
The migration copies the old file to the backup instead of moving it and replaces the file atomically, only after the migration succeeded.
An explicit save keeps a copy of a file that could not be loaded and serializes the configuration before it opens the file.
The configuration guide describes the migration backup and what happens to a file that cannot be loaded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
Christin
2026-11-20 18:39:14 +01:00
committed by Bobby Noelte
co-authored by Claude Opus 5.5
parent 887bae551b
commit f3773de8f8
5 changed files with 236 additions and 32 deletions
+11
View File
@@ -98,6 +98,17 @@ found, a default configuration file is created, and the default settings are wri
location of the created configuration file follows the same order in which EOS searches for location of the created configuration file follows the same order in which EOS searches for
configuration files, and it depends on whether the relevant environment variables are set. configuration files, and it depends on whether the relevant environment variables are set.
A configuration file of an older EOS version is migrated to the current version. The old file is
kept as a backup next to it (`EOS.config.<timestamp>`). If the migration fails, the file is left
as it is.
If the configuration file cannot be loaded, e.g. because of a JSON syntax error or a failed
migration, EOS logs an error and runs with the default configuration. It then does not save the
configuration automatically, so the defaults never replace the file. Fix the file and reload it
with `POST /v1/config/reset` or a restart of EOS. `PUT /v1/config/file` saves the current
configuration anyway; it keeps a copy of the file that could not be loaded as
`EOS.config.unreadable.<timestamp>`.
Use the following endpoints to interact with the configuration file: Use the following endpoints to interact with the configuration file:
- `PUT /v1/config/file`: Save the current configuration to the configuration file. - `PUT /v1/config/file`: Save the current configuration to the configuration file.
+38 -6
View File
@@ -11,6 +11,7 @@ Key features:
import json import json
import os import os
import shutil
import sys import sys
import tempfile import tempfile
from copy import deepcopy from copy import deepcopy
@@ -463,6 +464,9 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
"with_file_secret_settings": True, "with_file_secret_settings": True,
} }
_config_file_path: ClassVar[Optional[Path]] = None _config_file_path: ClassVar[Optional[Path]] = None
# Why the configuration file could not be loaded, None if it was loaded. The automatic save
# never replaces such a file by the default configuration EOS falls back to.
_config_file_load_error: ClassVar[Optional[str]] = None
_config_autosave: ClassVar[str] = "" _config_autosave: ClassVar[str] = ""
# Settings provided at runtime, e.g. by the REST interface. Highest priority after CLI. # Settings provided at runtime, e.g. by the REST interface. Highest priority after CLI.
_runtime_settings: ClassVar[dict[str, Any]] = {} _runtime_settings: ClassVar[dict[str, Any]] = {}
@@ -707,6 +711,7 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
Ensures the config file exists and creates a backup if necessary. Ensures the config file exists and creates a backup if necessary.
""" """
cls._config_file_load_error = None
if not cls._init_config_eos.get("with_file_settings", True): if not cls._init_config_eos.get("with_file_settings", True):
logger.debug("Config initialisation with file settings is disabled.") logger.debug("Config initialisation with file settings is disabled.")
return {} return {}
@@ -724,9 +729,17 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
settings = pydantic_settings.JsonConfigSettingsSource( settings = pydantic_settings.JsonConfigSettingsSource(
settings_cls, json_file=config_file settings_cls, json_file=config_file
)() )()
else:
cls._config_file_load_error = "the file could not be read or migrated"
except Exception as ex: except Exception as ex:
cls._config_file_load_error = str(ex)
if cls._config_file_load_error is not None:
logger.error( logger.error(
f"Error reading config file '{config_file}' (falling back to default config): {ex}" f"Error reading config file '{config_file}' (falling back to default config): "
f"{cls._config_file_load_error}. The configuration is not saved automatically "
"until the file is loaded, so the file is kept. Fix the file and reload it "
"(POST /v1/config/reset or restart EOS), or save the current configuration "
"explicitly (PUT /v1/config/file), which keeps a copy of the file."
) )
return settings return settings
@@ -1227,24 +1240,43 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults):
def to_config_file(self) -> None: def to_config_file(self) -> None:
"""Saves the current configuration to the configuration file. """Saves the current configuration to the configuration file.
Also updates the configuration file settings. Also updates the configuration file settings. If the configuration file could not be
loaded, a copy of it is kept as ``<stem>.unreadable.<timestamp>`` next to it.
Raises: Raises:
ValueError: If the configuration file path is not specified or can not be written to. ValueError: If the configuration file path is not specified or can not be written to.
OSError: If the copy of a configuration file that could not be loaded fails.
""" """
if not self.general.config_file_path: config_file_path = self.general.config_file_path
if not config_file_path:
raise ValueError("Configuration file path unknown.") raise ValueError("Configuration file path unknown.")
with self.general.config_file_path.open("w", encoding="utf-8", newline="\n") as f_out: config_json = self.to_config_json()
f_out.write(self.to_config_json()) if ConfigEOS._config_file_load_error is not None and config_file_path.exists():
logger.info(f"Saved configuration to '{self.general.config_file_path}'.") # The current configuration does not hold the content of the file - keep it.
unreadable_file_path = config_file_path.with_name(
f"{config_file_path.stem}.unreadable.{to_datetime(as_string='YYYYMMDDHHmmss')}"
)
shutil.copy2(config_file_path, unreadable_file_path)
logger.warning(
f"Kept a copy of the configuration file that could not be loaded "
f"as '{unreadable_file_path}'."
)
with config_file_path.open("w", encoding="utf-8", newline="\n") as f_out:
f_out.write(config_json)
ConfigEOS._config_file_load_error = None
logger.info(f"Saved configuration to '{config_file_path}'.")
def autosave(self) -> None: def autosave(self) -> None:
"""Saves the current configuration if AUTOMATIC save mode is configured. """Saves the current configuration if AUTOMATIC save mode is configured.
Tries to avoid save operation if there are no changes between last and actual save. Tries to avoid save operation if there are no changes between last and actual save.
A configuration file that could not be loaded is never saved automatically: the current
configuration fell back to the defaults and would replace the content of the file.
""" """
if self.general.config_save_mode != ConfigSaveMode.AUTOMATIC: if self.general.config_save_mode != ConfigSaveMode.AUTOMATIC:
return return
if ConfigEOS._config_file_load_error is not None:
return
config_str = self.to_config_json() config_str = self.to_config_json()
if config_str != ConfigEOS._config_autosave: if config_str != ConfigEOS._config_autosave:
+56 -26
View File
@@ -1,7 +1,10 @@
"""Migrate config file to actual version.""" """Migrate config file to actual version."""
import json import json
import os
import shutil import shutil
import stat
import tempfile
import types import types
from pathlib import Path from pathlib import Path
from typing import ( from typing import (
@@ -611,9 +614,41 @@ def remove_empty(obj: dict) -> dict:
return obj return obj
def _replace_config_file(config_file: Path, content: str) -> None:
"""Replace the configuration file atomically.
The content is written to a temporary file next to the configuration file, which then
replaces it. If writing fails, the configuration file is left untouched. The new file keeps
the permission bits of the old one.
Args:
config_file (Path): The existing configuration file.
content (str): The new content of the configuration file.
Raises:
OSError: If the temporary file can not be written or can not replace the file.
"""
fd, tmp_name = tempfile.mkstemp(
dir=config_file.parent, prefix=f".{config_file.name}.", suffix=".tmp"
)
try:
with os.fdopen(fd, "w", encoding="utf-8") as f_out:
f_out.write(content)
f_out.flush()
os.fsync(f_out.fileno())
os.chmod(tmp_name, stat.S_IMODE(config_file.stat().st_mode))
os.replace(tmp_name, config_file)
except BaseException:
Path(tmp_name).unlink(missing_ok=True)
raise
def migrate_config_file(config_file: Path, backup_file: Path) -> bool: def migrate_config_file(config_file: Path, backup_file: Path) -> bool:
"""Migrate configuration file to the current version. """Migrate configuration file to the current version.
Only a successful migration replaces the file; the old file is copied to the backup file
right before. A failed migration leaves the file untouched and makes no backup.
Returns: Returns:
bool: True if up-to-date or successfully migrated, False on failure. bool: True if up-to-date or successfully migrated, False on failure.
""" """
@@ -643,21 +678,6 @@ def migrate_config_file(config_file: Path, backup_file: Path) -> bool:
) )
try: try:
# Backup existing file - we already know it is existing
try:
config_file.replace(backup_file)
logger.info(f"Backed up old configuration to '{backup_file}'.")
except Exception as e_replace:
try:
shutil.copy(config_file, backup_file)
logger.info(
f"Could not replace; copied old configuration to '{backup_file}' instead."
)
except Exception as e_copy:
logger.warning(
f"Failed to backup existing config (replace: {e_replace}; copy: {e_copy}). Continuing without backup."
)
from akkudoktoreos.config.config import SettingsEOSDefaults from akkudoktoreos.config.config import SettingsEOSDefaults
# Strip computed fields # Strip computed fields
@@ -666,19 +686,29 @@ def migrate_config_file(config_file: Path, backup_file: Path) -> bool:
# Migrate config data # Migrate config data
new_config = migrate_config_data(config_data) new_config = migrate_config_data(config_data)
# Need model_dump_json (not model_dump) because of special serialisation.
json_str = new_config.model_dump_json(
exclude_computed_fields=True,
exclude_defaults=True,
exclude_none=True,
by_alias=True,
)
cleaned = remove_empty(json.loads(json_str))
json_str = json.dumps(cleaned, indent=4, ensure_ascii=False)
# Backup existing file - we already know it is existing. Copy it: the file stays in
# place until the migrated configuration replaces it.
try:
shutil.copy2(config_file, backup_file)
logger.info(f"Backed up old configuration to '{backup_file}'.")
except Exception as e_copy:
logger.warning(
f"Failed to backup existing config ({e_copy}). Continuing without backup."
)
# Write migrated configuration # Write migrated configuration
try: try:
with config_file.open("w", encoding="utf-8", newline=None) as f_out: _replace_config_file(config_file, json_str)
# Need model_dump_json (not model_dump) because of special serialisation.
json_str = new_config.model_dump_json(
exclude_computed_fields=True,
exclude_defaults=True,
exclude_none=True,
by_alias=True,
)
cleaned = remove_empty(json.loads(json_str))
json_str = json.dumps(cleaned, indent=4, ensure_ascii=False)
f_out.write(json_str)
except Exception as e_write: except Exception as e_write:
logger.error(f"Failed to write migrated configuration to '{config_file}': {e_write}") logger.error(f"Failed to write migrated configuration to '{config_file}': {e_write}")
return False return False
+85
View File
@@ -10,6 +10,7 @@ import pytest
from pydantic import ValidationError from pydantic import ValidationError
from akkudoktoreos.config.config import ConfigEOS, GeneralSettings from akkudoktoreos.config.config import ConfigEOS, GeneralSettings
from akkudoktoreos.core.version import __version__
from akkudoktoreos.devices.devices import DevicesCommonSettings from akkudoktoreos.devices.devices import DevicesCommonSettings
@@ -843,6 +844,90 @@ class TestConfigEOSToConfigFile:
assert reloaded.server.port == 9000 assert reloaded.server.port == 9000
class TestUnreadableConfigFile:
"""A configuration file that can not be loaded is never replaced by the defaults.
EOS falls back to the default configuration if its configuration file can not be read or
migrated. The automatic save must not write these defaults over the file of the user.
"""
# A trailing comma - a typical manual editing error.
UNREADABLE = (
'{"general": {"version": "' + __version__ + '", "latitude": 48.1},\n'
' "server": {"port": 9999},}\n'
).encode("utf-8")
@pytest.fixture
def unreadable_config_file(
self, uncreated_config: Path, monkeypatch: pytest.MonkeyPatch
) -> Path:
"""Write an unreadable config file; get_config(init=True) starts from it."""
uncreated_config.write_bytes(self.UNREADABLE)
# Forget the last automatic save of another test.
monkeypatch.setattr(ConfigEOS, "_config_autosave", "")
return uncreated_config
def test_autosave_keeps_unreadable_file(self, unreadable_config_file: Path) -> None:
from akkudoktoreos.core.coreabc import get_config
config = get_config(init=True)
assert config.general.latitude == GeneralSettings.model_fields["latitude"].default
config.autosave()
config.merge_settings_from_dict({"general": {"longitude": 11.5}})
config.autosave()
assert unreadable_config_file.read_bytes() == self.UNREADABLE
def test_autosave_keeps_file_of_failed_migration(
self, uncreated_config: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from akkudoktoreos.config import configmigrate
from akkudoktoreos.core.coreabc import get_config
content = json.dumps({"general": {"version": "0.0.0-old", "latitude": 48.1}}).encode()
uncreated_config.write_bytes(content)
monkeypatch.setattr(ConfigEOS, "_config_autosave", "")
monkeypatch.setattr(
configmigrate, "migrate_config_data", Mock(side_effect=RuntimeError("migration failed"))
)
config = get_config(init=True)
config.autosave()
assert uncreated_config.read_bytes() == content
def test_save_keeps_copy_of_unreadable_file(self, unreadable_config_file: Path) -> None:
"""An explicit save replaces the file, but keeps a copy of it."""
from akkudoktoreos.core.coreabc import get_config
config = get_config(init=True)
config.merge_settings_from_dict({"general": {"longitude": 11.5}})
config.to_config_file()
saved = json.loads(unreadable_config_file.read_text(encoding="utf-8"))
assert saved["general"]["longitude"] == 11.5
copies = list(unreadable_config_file.parent.glob("EOS.config.unreadable.*"))
assert [copy.read_bytes() for copy in copies] == [self.UNREADABLE]
def test_autosave_resumes_when_file_is_loaded(self, unreadable_config_file: Path) -> None:
from akkudoktoreos.core.coreabc import get_config
config = get_config(init=True)
unreadable_config_file.write_text(
json.dumps({"general": {"version": __version__, "latitude": 48.1}}), encoding="utf-8"
)
config.reset_settings()
config.merge_settings_from_dict({"general": {"longitude": 11.5}})
config.autosave()
saved = json.loads(unreadable_config_file.read_text(encoding="utf-8"))
assert saved["general"]["latitude"] == 48.1
assert saved["general"]["longitude"] == 11.5
class TestDeviceSettings: class TestDeviceSettings:
def test_device_map_supplies_stable_identity(self): def test_device_map_supplies_stable_identity(self):
raw = {"batteries": {"house": {"profile_adjustment": {"nominal_capacity_wh": 12000}}}} raw = {"batteries": {"house": {"profile_adjustment": {"nominal_capacity_wh": 12000}}}}
+46
View File
@@ -1,9 +1,12 @@
# Test data directory and known migration pairs # Test data directory and known migration pairs
import copy import copy
import json import json
import os
import shutil import shutil
import stat
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
from unittest.mock import Mock
import pytest import pytest
@@ -144,6 +147,49 @@ class TestConfigMigration:
assert result is True assert result is True
assert not backup_file.exists(), "No backup should be made if config is already current." assert not backup_file.exists(), "No backup should be made if config is already current."
def test_migrate_config_file_backs_up_by_copy(self, tmp_config_file: Path) -> None:
"""The backup is a copy of the old file, the migrated file keeps its permissions."""
tmp_config_file.chmod(0o640)
mode = stat.S_IMODE(tmp_config_file.stat().st_mode)
original = tmp_config_file.read_bytes()
backup_file = tmp_config_file.with_suffix(".bak")
assert configmigrate.migrate_config_file(tmp_config_file, backup_file) is True
assert backup_file.read_bytes() == original
migrated_data = json.loads(tmp_config_file.read_text(encoding="utf-8"))
assert migrated_data["general"]["version"] == __version__
assert stat.S_IMODE(tmp_config_file.stat().st_mode) == mode
assert not list(tmp_config_file.parent.glob("*.tmp"))
def test_migrate_config_file_failure_keeps_original(
self, tmp_config_file: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A migration that raises leaves the old file in place and needs no backup."""
original = tmp_config_file.read_bytes()
backup_file = tmp_config_file.with_suffix(".bak")
monkeypatch.setattr(
configmigrate, "migrate_config_data", Mock(side_effect=RuntimeError("migration failed"))
)
assert configmigrate.migrate_config_file(tmp_config_file, backup_file) is False
assert tmp_config_file.read_bytes() == original
assert not backup_file.exists()
def test_migrate_config_file_write_failure_keeps_original(
self, tmp_config_file: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A migrated file that can not replace the old one leaves the old file in place."""
original = tmp_config_file.read_bytes()
backup_file = tmp_config_file.with_suffix(".bak")
monkeypatch.setattr(os, "replace", Mock(side_effect=OSError("replace failed")))
assert configmigrate.migrate_config_file(tmp_config_file, backup_file) is False
assert tmp_config_file.read_bytes() == original
assert not list(tmp_config_file.parent.glob("*.tmp"))
@pytest.mark.parametrize("old_file, expected_file", MIGRATION_PAIRS) @pytest.mark.parametrize("old_file, expected_file", MIGRATION_PAIRS)
def test_migrate_old_version_config(self, tmp_path: Path, old_file: Path, expected_file: Path): def test_migrate_old_version_config(self, tmp_path: Path, old_file: Path, expected_file: Path):