From 1a5bdcf3d6a65dadee180aa7cdd7fa6b4ad8d2d5 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Thu, 26 Nov 2026 16:14:21 +0100 Subject: [PATCH 1/2] Declare each config type's current version in one table - versioning.CURRENT_CONFIG_VERSIONS maps each versioned config type to its current schema version, ProjectConfig and PoseConfig at 0; CURRENT_CONFIG_VERSION is gone - migrate_config targets the version of the type it migrates; a type not listed is at version 0 - A listed config type built without config_version takes its current version; an unlisted one keeps its own default - Tests set the version of the type they exercise instead of a global one --- dlccore/config/base_config.py | 23 +++++++---- dlccore/config/versioning.py | 26 ++++++++---- tests/config/conftest.py | 5 ++- tests/config/test_config_breakage.py | 2 +- tests/config/test_project_config.py | 16 ++++---- tests/config/test_versioning.py | 59 ++++++++++++++++++++++++---- 6 files changed, 100 insertions(+), 31 deletions(-) diff --git a/dlccore/config/base_config.py b/dlccore/config/base_config.py index 5a131b0..6f21e29 100644 --- a/dlccore/config/base_config.py +++ b/dlccore/config/base_config.py @@ -325,14 +325,15 @@ class DLCVersionedConfig(DLCBaseConfig): Additional behavior: - - `migrate_before_validate` upgrades raw dicts to `CURRENT_CONFIG_VERSION`. + - `from_dict` migrates raw dicts to the type's version in `versioning.CURRENT_CONFIG_VERSIONS`, which a + config built without `config_version` also takes, if its type is listed there. - Tracks fields modified after load; `to_yaml` can log changes and mark clean. - Patches `__setattr__` once per class to record dirty fields while delegating alias warnings to the base `__setattr__`. """ config_version: int = Field( - default=versioning.CURRENT_CONFIG_VERSION, + default=0, json_schema_extra={"comment": "Config schema version. Do not edit manually."}, ) @@ -346,13 +347,21 @@ class DLCVersionedConfig(DLCBaseConfig): @classmethod def from_dict(cls, cfg_dict: dict) -> Self: - cfg_dict = versioning.migrate_config( - cfg_dict, - config_type=cls.__name__, - target_version=versioning.CURRENT_CONFIG_VERSION, - ) + cfg_dict = versioning.migrate_config(cfg_dict, config_type=cls.__name__) return super().from_dict(cfg_dict) + @model_validator(mode="before") + @classmethod + def default_config_version(cls, data: Any) -> Any: + """Give a listed config type built without ``config_version`` its current version; others keep the default.""" + if cls.__name__ not in versioning.CURRENT_CONFIG_VERSIONS: + return data + if isinstance(data, ArgsKwargs): + data = cls._args_kwargs_to_dict(data) + if isinstance(data, dict) and "config_version" not in data: + return {**data, "config_version": versioning.current_config_version(cls.__name__)} + return data + # ------------------------------------------------------------------ # Serialization # ------------------------------------------------------------------ diff --git a/dlccore/config/versioning.py b/dlccore/config/versioning.py index e698131..bd26e82 100644 --- a/dlccore/config/versioning.py +++ b/dlccore/config/versioning.py @@ -24,9 +24,18 @@ logger = logging.getLogger(__name__) -# Current configuration schema version -# Increment this when making breaking changes to the config structure -CURRENT_CONFIG_VERSION = 0 +# Current schema version of each versioned config type, by class name; the one place these versions are declared. +# Bump a type's entry when making a breaking change to its structure, and register the migrations to and from it. +# A type not listed here is at version 0. +CURRENT_CONFIG_VERSIONS: dict[str, int] = { + "ProjectConfig": 0, + "PoseConfig": 0, +} + + +def current_config_version(config_type: str) -> int: + """Return the current schema version of ``config_type``, a ``DLCVersionedConfig`` subclass name; 0 if unlisted.""" + return CURRENT_CONFIG_VERSIONS.get(config_type, 0) # Version registry: maps (config_type, from_version, to_version) -> migration function. @@ -164,7 +173,7 @@ def get_config_version(config: dict) -> int: def migrate_config( config: dict, config_type: str, - target_version: int = CURRENT_CONFIG_VERSION, + target_version: int | None = None, ) -> dict: """Migrate a configuration to the target version. @@ -176,7 +185,7 @@ def migrate_config( config: Configuration dictionary to migrate. config_type: Class name of the config being migrated (e.g. ``"ProjectConfig"``). Only migrations registered for this type are applied. - target_version: Target version to migrate to (default: current). + target_version: Target version to migrate to; ``None`` for ``config_type``'s current version. Returns: Migrated configuration dictionary. @@ -185,12 +194,15 @@ def migrate_config( ValueError: If migration chain is incomplete or target version is invalid. """ current_version = get_config_version(config) + latest_version = current_config_version(config_type) + if target_version is None: + target_version = latest_version if current_version == target_version: return config - if target_version > CURRENT_CONFIG_VERSION: - raise ValueError(f"Target version {target_version} exceeds current version {CURRENT_CONFIG_VERSION}") + if target_version > latest_version: + raise ValueError(f"Target version {target_version} exceeds current version {latest_version} of {config_type}") direction = "upgrade" if target_version > current_version else "downgrade" logger.info( diff --git a/tests/config/conftest.py b/tests/config/conftest.py index 109bafb..48bce42 100644 --- a/tests/config/conftest.py +++ b/tests/config/conftest.py @@ -29,10 +29,11 @@ def isolated_migration_registry(monkeypatch): @pytest.fixture def register_toy_migrations(monkeypatch): - """Register v98 <-> v99 toy migrations for the given config_type(s).""" - monkeypatch.setattr(versioning, "CURRENT_CONFIG_VERSION", _TOY_VERSION_NEW) + """Register v98 <-> v99 toy migrations for the given config_type(s), and make v99 their current version.""" def register_pair(config_type: str) -> None: + monkeypatch.setitem(versioning.CURRENT_CONFIG_VERSIONS, config_type, _TOY_VERSION_NEW) + @register_migration(_TOY_VERSION_OLD, _TOY_VERSION_NEW, config_type=config_type) def up(config: dict) -> dict: if _LEGACY_FIELD in config: diff --git a/tests/config/test_config_breakage.py b/tests/config/test_config_breakage.py index 6622414..0b7e456 100644 --- a/tests/config/test_config_breakage.py +++ b/tests/config/test_config_breakage.py @@ -284,7 +284,7 @@ def test_migration_skipped_on_typed_construction(monkeypatch, kwargs): ``MyCfg(epochs=100)`` is current-schema construction, not loading an old file. Migration should only run via ``from_dict`` / ``from_yaml``. """ - monkeypatch.setattr(versioning, "CURRENT_CONFIG_VERSION", 1) + monkeypatch.setitem(versioning.CURRENT_CONFIG_VERSIONS, "_TypedConstructionCfg", 1) cfg = _TypedConstructionCfg(**kwargs) diff --git a/tests/config/test_project_config.py b/tests/config/test_project_config.py index 19ad559..8803018 100644 --- a/tests/config/test_project_config.py +++ b/tests/config/test_project_config.py @@ -16,7 +16,9 @@ import pytest from dlccore.config import ProjectConfig, read_config_as_dict -from dlccore.config.versioning import CURRENT_CONFIG_VERSION +from dlccore.config.versioning import current_config_version + +PROJECT_CONFIG_VERSION = current_config_version("ProjectConfig") # ----------------------------------------------------------------------------- # Basic construction / defaults @@ -26,7 +28,7 @@ class TestProjectConfigDefaults: def test_defaults(self): cfg = ProjectConfig() - assert cfg.config_version == CURRENT_CONFIG_VERSION + assert cfg.config_version == PROJECT_CONFIG_VERSION assert cfg.engine == "pytorch" assert cfg.Task == "" assert isinstance(cfg.project_path, Path) @@ -295,7 +297,7 @@ def test_to_yaml_writes_config_version(self, tmp_path): ProjectConfig(project_path=tmp_path).to_yaml(config_path) saved = read_config_as_dict(config_path) assert "config_version" in saved - assert saved["config_version"] == CURRENT_CONFIG_VERSION + assert saved["config_version"] == PROJECT_CONFIG_VERSION # ----------------------------------------------------------------------------- @@ -305,9 +307,9 @@ def test_to_yaml_writes_config_version(self, tmp_path): class TestProjectConfigVersioning: def test_no_migration_log_for_current_version_yaml(self, tmp_path, caplog): - """Loading a config already at CURRENT_CONFIG_VERSION emits no migration INFO log.""" + """Loading a config already at PROJECT_CONFIG_VERSION emits no migration INFO log.""" config_path = tmp_path / "config.yaml" - config_path.write_text(f"config_version: {CURRENT_CONFIG_VERSION}\nproject_path: {tmp_path}\nengine: pytorch\n") + config_path.write_text(f"config_version: {PROJECT_CONFIG_VERSION}\nproject_path: {tmp_path}\nengine: pytorch\n") with caplog.at_level(logging.INFO, logger="dlccore.config.versioning"): ProjectConfig.from_yaml(config_path) @@ -319,7 +321,7 @@ def test_unversioned_yaml_treated_as_v0(self, tmp_path): config_path = tmp_path / "config.yaml" config_path.write_text(f"project_path: {tmp_path}\nengine: pytorch\n") cfg = ProjectConfig.from_yaml(config_path) - assert cfg.config_version == CURRENT_CONFIG_VERSION + assert cfg.config_version == PROJECT_CONFIG_VERSION # ----------------------------------------------------------------------------- @@ -327,7 +329,7 @@ def test_unversioned_yaml_treated_as_v0(self, tmp_path): # # Each test here describes a field that is exposed as a read-only property today # because promoting it to a real schema field requires bumping -# CURRENT_CONFIG_VERSION and writing the migration. They are marked strict xfail +# PROJECT_CONFIG_VERSION and writing the migration. They are marked strict xfail # so that the migration landing turns them into failures, as a reminder to drop # the property and the marker together. # ----------------------------------------------------------------------------- diff --git a/tests/config/test_versioning.py b/tests/config/test_versioning.py index eafd6cb..ea35d71 100644 --- a/tests/config/test_versioning.py +++ b/tests/config/test_versioning.py @@ -76,7 +76,7 @@ def test_migrate_config_does_not_mutate_input(): def test_migrate_config_target_exceeds_current_raises(monkeypatch): - monkeypatch.setattr(versioning, "CURRENT_CONFIG_VERSION", 99) + monkeypatch.setitem(versioning.CURRENT_CONFIG_VERSIONS, _TOY_CONFIG_TYPE, 99) with pytest.raises(ValueError, match="Target version .* exceeds current"): migrate_config({"config_version": 0}, config_type=_TOY_CONFIG_TYPE, target_version=100) @@ -170,7 +170,7 @@ class ToyConfig(DLCVersionedConfig): def test_config_with_legacy_field_raises_without_migration(monkeypatch, ToyConfigWithValidField): """Legacy unknown field raises validation error when no migration is registered.""" - monkeypatch.setattr(versioning, "CURRENT_CONFIG_VERSION", _TOY_VERSION_OLD) + monkeypatch.setitem(versioning.CURRENT_CONFIG_VERSIONS, "ToyConfig", _TOY_VERSION_OLD) config_with_legacy_field = { "config_version": _TOY_VERSION_OLD, "this_fieldname_is_not_in_project_config": "some_value", @@ -181,7 +181,7 @@ def test_config_with_legacy_field_raises_without_migration(monkeypatch, ToyConfi def test_config_after_migration_accepts_renamed_field(monkeypatch, ToyConfigWithValidField): """Registering a migration renames the legacy field so the model accepts the config.""" - monkeypatch.setattr(versioning, "CURRENT_CONFIG_VERSION", _TOY_VERSION_NEW) + monkeypatch.setitem(versioning.CURRENT_CONFIG_VERSIONS, "ToyConfig", _TOY_VERSION_NEW) config_with_legacy_field = { "config_version": _TOY_VERSION_OLD, "this_fieldname_is_not_in_project_config": "some_value", @@ -253,8 +253,9 @@ def test_migration_then_alias_on_old_version_with_deprecated_alias( assert cfg.toy_new_field == "both_steps" -def test_from_dict_runs_migration(_migrate_then_alias_current): +def test_from_dict_runs_migration(monkeypatch): """Legacy dicts loaded via from_dict are migrated before validation.""" + monkeypatch.setitem(versioning.CURRENT_CONFIG_VERSIONS, "_KwOnlyVersioned", _TOY_VERSION_NEW) class _KwOnlyVersioned(DLCVersionedConfig): config_version: int = _TOY_VERSION_NEW @@ -349,8 +350,8 @@ def _chain_v53_to_v52(config: dict) -> dict: @pytest.fixture def chain_migrations(monkeypatch): - """Register v50↔v53 chain and set CURRENT_CONFIG_VERSION=53.""" - monkeypatch.setattr(versioning, "CURRENT_CONFIG_VERSION", _V53) + """Register v50↔v53 chain and make v53 the chain type's current version.""" + monkeypatch.setitem(versioning.CURRENT_CONFIG_VERSIONS, _CHAIN_CONFIG_TYPE, _V53) _register_chain_migrations() @@ -902,7 +903,7 @@ class TestVersionedConfigValidateAssignment: @pytest.fixture(autouse=True) def _default_version(self, monkeypatch): - monkeypatch.setattr(versioning, "CURRENT_CONFIG_VERSION", 0) + monkeypatch.setitem(versioning.CURRENT_CONFIG_VERSIONS, "ValidatedMigratingConfig", 0) def test_valid_assignment_takes_effect(self): cfg = ValidatedMigratingConfig() @@ -919,3 +920,47 @@ def test_coercion_applied_on_assignment(self): cfg = ValidatedMigratingConfig() cfg.count = True # coerced to 1 assert cfg.count == 1 + + +# ----------------------------------------------------------------------------- +# Per-type current versions +# ----------------------------------------------------------------------------- + + +def test_each_versioned_config_type_has_its_own_current_version(monkeypatch): + monkeypatch.setitem(versioning.CURRENT_CONFIG_VERSIONS, "PoseConfig", 3) + + assert versioning.current_config_version("PoseConfig") == 3 + assert versioning.current_config_version("ProjectConfig") == 0 + + +def test_an_unlisted_config_type_is_at_version_zero(): + assert "NotAVersionedConfig" not in versioning.CURRENT_CONFIG_VERSIONS + assert versioning.current_config_version("NotAVersionedConfig") == 0 + + +def test_migrate_config_targets_the_current_version_of_its_type(register_toy_migrations): + register_toy_migrations("PerTypeToyConfig") + + migrated = migrate_config({"config_version": _TOY_VERSION_OLD, _LEGACY_FIELD: "x"}, config_type="PerTypeToyConfig") + + assert migrated[_NEW_FIELD] == "x" + # Control: another type's version is untouched, so the same dict is already current for it. + assert migrate_config({"config_version": 0}, config_type="ProjectConfig") == {"config_version": 0} + + +def test_a_listed_config_type_built_without_a_version_takes_its_current_version(monkeypatch): + class ListedVersionedConfig(DLCVersionedConfig): + name: str = "" + + monkeypatch.setitem(versioning.CURRENT_CONFIG_VERSIONS, "ListedVersionedConfig", 7) + + assert ListedVersionedConfig().config_version == 7 + assert ListedVersionedConfig(config_version=5).config_version == 5 + + +def test_an_unlisted_config_type_keeps_its_own_version_default(): + class UnlistedVersionedConfig(DLCVersionedConfig): + config_version: int = 4 + + assert UnlistedVersionedConfig().config_version == 4 From 61f98ad1ed2e9cb234a2322b346e4b95e0661aa4 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Fri, 4 Dec 2026 16:20:05 +0100 Subject: [PATCH 2/2] docstring edits --- dlccore/config/base_config.py | 2 +- dlccore/config/versioning.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dlccore/config/base_config.py b/dlccore/config/base_config.py index 6f21e29..e72ef8e 100644 --- a/dlccore/config/base_config.py +++ b/dlccore/config/base_config.py @@ -353,7 +353,7 @@ def from_dict(cls, cfg_dict: dict) -> Self: @model_validator(mode="before") @classmethod def default_config_version(cls, data: Any) -> Any: - """Give a listed config type built without ``config_version`` its current version; others keep the default.""" + """Give a listed config type built without ``config_version`` the current version; otherwise the default.""" if cls.__name__ not in versioning.CURRENT_CONFIG_VERSIONS: return data if isinstance(data, ArgsKwargs): diff --git a/dlccore/config/versioning.py b/dlccore/config/versioning.py index bd26e82..a2e2f47 100644 --- a/dlccore/config/versioning.py +++ b/dlccore/config/versioning.py @@ -24,9 +24,9 @@ logger = logging.getLogger(__name__) -# Current schema version of each versioned config type, by class name; the one place these versions are declared. +# Current schema version for each versioned config type # Bump a type's entry when making a breaking change to its structure, and register the migrations to and from it. -# A type not listed here is at version 0. +# A type not listed here is at version 0 by default. CURRENT_CONFIG_VERSIONS: dict[str, int] = { "ProjectConfig": 0, "PoseConfig": 0,