Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions dlccore/config/base_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."},
)

Expand All @@ -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`` the current version; otherwise 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
# ------------------------------------------------------------------
Expand Down
26 changes: 19 additions & 7 deletions dlccore/config/versioning.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 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 by default.
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.
Expand Down Expand Up @@ -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.

Expand All @@ -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.
Expand All @@ -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(
Expand Down
5 changes: 3 additions & 2 deletions tests/config/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion tests/config/test_config_breakage.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
16 changes: 9 additions & 7 deletions tests/config/test_project_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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


# -----------------------------------------------------------------------------
Expand All @@ -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)

Expand All @@ -319,15 +321,15 @@ 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


# -----------------------------------------------------------------------------
# Fields awaiting the next schema version bump
#
# 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.
# -----------------------------------------------------------------------------
Expand Down
59 changes: 52 additions & 7 deletions tests/config/test_versioning.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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",
Expand All @@ -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",
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()


Expand Down Expand Up @@ -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()
Expand All @@ -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
Loading