From 68e06c104c43a8425fe18d9423e8fb62afec7f00 Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Thu, 26 Nov 2026 15:10:42 +0100 Subject: [PATCH 1/2] Copy project config discovery and validation --- dlccore/project/discovery/config.py | 78 ++++ dlccore/project/schemas/base/finding_codes.py | 68 ++++ dlccore/project/validation/__init__.py | 3 + dlccore/project/validation/config.py | 211 ++++++++++ dlccore/project/validation/context.py | 37 ++ .../discovery/test_config_discovery.py | 116 ++++++ .../validation/test_config_validation.py | 385 ++++++++++++++++++ 7 files changed, 898 insertions(+) create mode 100644 dlccore/project/discovery/config.py create mode 100644 dlccore/project/validation/config.py create mode 100644 dlccore/project/validation/context.py create mode 100644 tests/project/discovery/test_config_discovery.py create mode 100644 tests/project/validation/test_config_validation.py diff --git a/dlccore/project/discovery/config.py b/dlccore/project/discovery/config.py new file mode 100644 index 0000000..31367a7 --- /dev/null +++ b/dlccore/project/discovery/config.py @@ -0,0 +1,78 @@ +# dlc_octopus/discovery/config.py +"""Read a project's config file without interpreting or validating its content.""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum +from pathlib import Path +from typing import Any + +from deeplabcut.core.config.utils import read_config_as_dict + + +class RawConfigReadStatus(str, Enum): + """Outcome of reading one config file from disk.""" + + OK = "ok" + READ_FAILED = "read_failed" + PARSE_FAILED = "parse_failed" + + +@dataclass(frozen=True) +class RawConfigRead: + """Internal result of reading one config file, before any validation.""" + + status: RawConfigReadStatus + raw_config: dict[str, Any] | None = None + declared_project_path: str | None = None + error_type: str | None = None + error_message: str | None = None + + +def discover_config_file( + config_path: Path, +) -> RawConfigRead: + """Read a config file and record what was found, without validating it. + + The existing DeepLabCut config reader performs YAML I/O. This function + does not migrate, validate, or interpret the loaded data beyond + extracting the declared project path as written. + """ + + try: + raw_config = read_config_as_dict(config_path) + except OSError as exc: + return RawConfigRead( + status=RawConfigReadStatus.READ_FAILED, + error_type=type(exc).__name__, + error_message=str(exc), + ) + except Exception as exc: + return RawConfigRead( + status=RawConfigReadStatus.PARSE_FAILED, + error_type=type(exc).__name__, + error_message=str(exc), + ) + + return RawConfigRead( + status=RawConfigReadStatus.OK, + raw_config=dict(raw_config), + declared_project_path=_declared_project_path(raw_config), + ) + + +def _declared_project_path( + raw_config: object, +) -> str | None: + """Return the project path as written; a ``Path`` would rewrite another platform's separators.""" + + if not isinstance(raw_config, dict): + return None + + value = raw_config.get("project_path") + + if not isinstance(value, (str, Path)) or not str(value): + return None + + return str(value) diff --git a/dlccore/project/schemas/base/finding_codes.py b/dlccore/project/schemas/base/finding_codes.py index 4c658ac..0983de3 100644 --- a/dlccore/project/schemas/base/finding_codes.py +++ b/dlccore/project/schemas/base/finding_codes.py @@ -91,6 +91,74 @@ class StructureFindingCode(FindingCode): ) +class ConfigFindingCode(FindingCode): + """Findings about reading, parsing and interpreting ``config.yaml``.""" + + CONFIG_READ_FAILED = ( + "CONFIG_READ_FAILED", + "The config file could not be read.", + Severity.ERROR, + ("error_type", "error_message"), + ) + CONFIG_PARSE_FAILED = ( + "CONFIG_PARSE_FAILED", + "The config file could not be parsed.", + Severity.ERROR, + ("error_type", "error_message"), + ) + CONFIG_VALIDATION_ERROR = ( + "CONFIG_VALIDATION_ERROR", + "The config file failed canonical schema validation.", + Severity.ERROR, + ("error_type", "error_message"), + ) + CONFIG_LOAD_FAILED = ( + "CONFIG_LOAD_FAILED", + "The config file could not be loaded through the canonical schema, for a reason other than a field " + "failing validation, such as a config version with no migration path.", + Severity.ERROR, + ("error_type", "error_message"), + ) + CONFIG_VERSION_UPGRADED = ( + "CONFIG_VERSION_UPGRADED", + "The config declares an older config version; DeepLabCut migrated it in memory to the current one.", + Severity.NOTE, + ("declared_version", "loaded_version"), + ) + CONFIG_VERSION_DOWNGRADED = ( + "CONFIG_VERSION_DOWNGRADED", + "The config declares a newer config version than this code reads; DeepLabCut migrated it down in memory, " + "which can drop fields.", + Severity.WARNING, + ("declared_version", "loaded_version"), + ) + CONFIG_NO_KEYPOINTS = ( + "CONFIG_NO_KEYPOINTS", + "The config loads but declares no keypoints.", + Severity.WARNING, + ("multianimal_project", "declared"), + ) + CONFIG_NULL_KEY_DEFAULTED = ( + "CONFIG_NULL_KEY_DEFAULTED", + "A config key is written with no value, so the DeepLabCut field default was used.", + Severity.NOTE, + ("default",), + ) + CONFIG_PROJECT_PATH_MISMATCH = ( + "CONFIG_PROJECT_PATH_MISMATCH", + "The project path declared in config.yaml does not match the project root observed. A declared path " + "probed as missing may also be an unreachable network location or a path from another platform.", + Severity.NOTE, + ("declared_project_path", "observed_project_root", "declared_path_probe", "error_type", "error_message"), + ) + CONFIG_PROJECT_PATH_NOT_ABSOLUTE = ( + "CONFIG_PROJECT_PATH_NOT_ABSOLUTE", + "The project path in config.yaml is missing, empty or relative, and cannot be compared with the project root.", + Severity.NOTE, + ("declared_project_path",), + ) + + def iter_finding_codes() -> tuple[FindingCode, ...]: """Return every declared finding code, namespace by namespace.""" diff --git a/dlccore/project/validation/__init__.py b/dlccore/project/validation/__init__.py index 3f447fe..43646a1 100644 --- a/dlccore/project/validation/__init__.py +++ b/dlccore/project/validation/__init__.py @@ -9,6 +9,7 @@ # Licensed under GNU Lesser General Public License v3.0 # +from .context import ValidationContext, build_validation_context from .requests import ( ProjectValidationRequest, ResourceValidationRequest, @@ -18,5 +19,7 @@ __all__ = [ "ProjectValidationRequest", "ResourceValidationRequest", + "ValidationContext", + "build_validation_context", "validate_project_structure", ] diff --git a/dlccore/project/validation/config.py b/dlccore/project/validation/config.py new file mode 100644 index 0000000..847e1f0 --- /dev/null +++ b/dlccore/project/validation/config.py @@ -0,0 +1,211 @@ +# dlc_octopus/validation/config.py +"""Validate a project's config file against the canonical DLC schema.""" + +from __future__ import annotations + +from pathlib import Path + +from deeplabcut.core.config import ProjectConfig +from pydantic import JsonValue, ValidationError + +from dlc_octopus.discovery.config import ( + RawConfigRead, + RawConfigReadStatus, + discover_config_file, +) +from dlc_octopus.schemas.base.finding_codes import ( + ConfigFindingCode, +) +from dlc_octopus.schemas.base.findings import ( + Finding, +) +from dlc_octopus.schemas.locations import one_per_project +from dlc_octopus.schemas.project_layout.config.observations import ( + ConfigObservation, + FailedConfigObservation, + ValidConfigObservation, +) +from dlc_octopus.schemas.project_layout.project import PROJECT_CONFIG + + +def validate_project_config( + config_path: Path, +) -> tuple[ConfigObservation, tuple[Finding, ...]]: + """Read and validate a canonical DLC config without modifying it. + + The existing DeepLabCut config reader performs YAML I/O. + ``ProjectConfig.from_dict`` performs validation against the canonical DLC schema. + + This function should not repair paths, modify the loaded model, or write + any project data. + """ + + raw = discover_config_file(config_path) + + if raw.status == RawConfigReadStatus.READ_FAILED: + return FailedConfigObservation( + config_path=config_path, + raw_config=None, + ), ( + Finding( + code=ConfigFindingCode.CONFIG_READ_FAILED, + **one_per_project(PROJECT_CONFIG), + path=config_path, + evidence=_read_failure_evidence(raw), + ), + ) + + if raw.status == RawConfigReadStatus.PARSE_FAILED: + return FailedConfigObservation( + config_path=config_path, + raw_config=None, + ), ( + Finding( + code=ConfigFindingCode.CONFIG_PARSE_FAILED, + **one_per_project(PROJECT_CONFIG), + path=config_path, + evidence=_read_failure_evidence(raw), + ), + ) + + try: + config = ProjectConfig.from_dict(dict(raw.raw_config)) + except ValidationError as exc: + findings = tuple( + Finding( + code=ConfigFindingCode.CONFIG_VALIDATION_ERROR, + **one_per_project(PROJECT_CONFIG), + path=config_path, + field_location=tuple(error["loc"]), + evidence={ + "error_type": str(error["type"]), + "error_message": str(error["msg"]), + }, + ) + for error in exc.errors( + include_url=False, + include_input=False, + ) + ) + + return FailedConfigObservation(config_path=config_path, raw_config=raw.raw_config), findings + except Exception as exc: + # ProjectConfig.from_dict migrates before it validates, and a migration + # re-raises with the original exception type, so the type is not knowable here. + return FailedConfigObservation(config_path=config_path, raw_config=raw.raw_config), ( + Finding( + code=ConfigFindingCode.CONFIG_LOAD_FAILED, + **one_per_project(PROJECT_CONFIG), + path=config_path, + evidence={ + "error_type": type(exc).__name__, + "error_message": str(exc), + }, + ), + ) + + return ValidConfigObservation( + config_path=config_path, + declared_project_path=raw.declared_project_path, + value=config, + ), ( + *_migration_findings(config, raw.raw_config, config_path), + *_no_keypoints_findings(config, raw.raw_config, config_path), + *_null_key_defaulted_findings(config, raw.raw_config, config_path), + ) + + +def _migration_findings( + config: ProjectConfig, + raw_config: dict, + config_path: Path, +) -> tuple[Finding, ...]: + """Report a config whose declared version DeepLabCut migrated in memory while loading it. + + A missing ``config_version`` is version 0, as DeepLabCut reads it. + """ + + declared = raw_config.get("config_version", 0) + loaded = config.config_version + + if not isinstance(declared, int) or declared == loaded: + return () + + code = ( + ConfigFindingCode.CONFIG_VERSION_UPGRADED if declared < loaded else ConfigFindingCode.CONFIG_VERSION_DOWNGRADED + ) + + return ( + Finding( + code=code, + **one_per_project(PROJECT_CONFIG), + path=config_path, + field_location=("config_version",), + evidence={"declared_version": declared, "loaded_version": loaded}, + ), + ) + + +def _no_keypoints_findings( + config: ProjectConfig, + raw_config: dict, + config_path: Path, +) -> tuple[Finding, ...]: + """Report a loaded config that declares no keypoints, with the keypoint fields as written. + + DeepLabCut normalises ``""``, ``[]`` and a missing key alike, so only the raw read tells them apart. + """ + + fields = ("multianimalbodyparts", "uniquebodyparts") if config.multianimalproject else ("bodyparts",) + + if any(getattr(config, field) for field in fields): + return () + + return ( + Finding( + code=ConfigFindingCode.CONFIG_NO_KEYPOINTS, + **one_per_project(PROJECT_CONFIG), + path=config_path, + field_location=fields[:1] if len(fields) == 1 else (), + evidence={ + "multianimal_project": bool(config.multianimalproject), + "declared": {field: raw_config[field] for field in fields if field in raw_config}, + }, + ), + ) + + +def _null_key_defaulted_findings( + config: ProjectConfig, + raw_config: dict, + config_path: Path, +) -> tuple[Finding, ...]: + """Report each key written with no value that DeepLabCut loaded as its field's default. + + A field that accepts ``None`` keeps it, so it is not reported. + """ + + loaded = config.model_dump(mode="json") + + return tuple( + Finding( + code=ConfigFindingCode.CONFIG_NULL_KEY_DEFAULTED, + **one_per_project(PROJECT_CONFIG), + path=config_path, + field_location=(field,), + evidence={"default": loaded[field]}, + ) + for field, value in raw_config.items() + if value is None and loaded.get(field) is not None + ) + + +def _read_failure_evidence( + raw: RawConfigRead, +) -> dict[str, JsonValue]: + """Return the declared evidence for a failed config read or parse.""" + + return { + "error_type": raw.error_type, + "error_message": raw.error_message, + } diff --git a/dlccore/project/validation/context.py b/dlccore/project/validation/context.py new file mode 100644 index 0000000..74ba8dd --- /dev/null +++ b/dlccore/project/validation/context.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from deeplabcut.core.config import ProjectConfig + +from dlc_octopus.schemas.base.core import FrozenModel +from dlc_octopus.schemas.project_layout.config.observations import ( + ValidConfigObservation, +) +from dlc_octopus.schemas.snapshots import ProjectSnapshot + + +class ValidationContext(FrozenModel): + """Canonical inputs available to config-dependent project validators.""" + + snapshot: ProjectSnapshot + config: ProjectConfig + # PoseConfig + # and any other validation metadata... + + +def build_validation_context( + snapshot: ProjectSnapshot, +) -> ValidationContext | None: + """Build config-dependent validation context when config is valid.""" + + observation = snapshot.config_observation + + if not isinstance( + observation, + ValidConfigObservation, + ): + return None + + return ValidationContext( + snapshot=snapshot, + config=observation.value, + ) diff --git a/tests/project/discovery/test_config_discovery.py b/tests/project/discovery/test_config_discovery.py new file mode 100644 index 0000000..5cf181c --- /dev/null +++ b/tests/project/discovery/test_config_discovery.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +from pathlib import Path + +import pytest + +from dlc_octopus.discovery.config import ( + RawConfigReadStatus, + _declared_project_path, + discover_config_file, +) + + +def test_discover_valid_config_reads_raw_data( + valid_project: Path, +) -> None: + config_path = valid_project / "config.yaml" + + raw = discover_config_file(config_path) + + assert raw.status == RawConfigReadStatus.OK + assert raw.raw_config is not None + assert raw.raw_config["scorer"] == "test-scorer" + assert raw.declared_project_path == str(valid_project) + assert raw.error_type is None + assert raw.error_message is None + + +def test_discover_missing_config_returns_read_failure( + tmp_path: Path, +) -> None: + config_path = tmp_path / "config.yaml" + + raw = discover_config_file(config_path) + + assert raw.status == RawConfigReadStatus.READ_FAILED + assert raw.raw_config is None + assert raw.error_type is not None + assert raw.error_message + + +def test_discover_empty_config_returns_parse_failure( + tmp_path: Path, +) -> None: + config_path = tmp_path / "config.yaml" + config_path.write_text( + "", + encoding="utf-8", + ) + + raw = discover_config_file(config_path) + + assert raw.status == RawConfigReadStatus.PARSE_FAILED + assert raw.raw_config is None + assert raw.error_type is not None + assert raw.error_message + + +def test_discover_config_file_does_not_modify_file( + valid_project: Path, +) -> None: + config_path = valid_project / "config.yaml" + + before = ( + config_path.read_bytes(), + config_path.stat().st_mtime_ns, + ) + + discover_config_file(config_path) + + after = ( + config_path.read_bytes(), + config_path.stat().st_mtime_ns, + ) + + assert after == before + + +@pytest.mark.parametrize( + ("raw_config", "expected"), + [ + ( + {"project_path": "/tmp/project"}, + "/tmp/project", + ), + ( + {"project_path": "C:\\data\\project"}, + "C:\\data\\project", + ), + ( + {"project_path": "relative/project"}, + "relative/project", + ), + ( + {"project_path": ""}, + None, + ), + ( + {"project_path": None}, + None, + ), + ( + {}, + None, + ), + ( + [], + None, + ), + ], +) +def test_declared_project_path( + raw_config: object, + expected: str | None, +) -> None: + assert _declared_project_path(raw_config) == expected diff --git a/tests/project/validation/test_config_validation.py b/tests/project/validation/test_config_validation.py new file mode 100644 index 0000000..c36ee94 --- /dev/null +++ b/tests/project/validation/test_config_validation.py @@ -0,0 +1,385 @@ +from __future__ import annotations + +import inspect +from pathlib import Path + +import numpy as np +import pytest +from deeplabcut.core.config import ProjectConfig, versioning +from deeplabcut.core.config.utils import write_config +from deeplabcut.core.config.versioning import CURRENT_CONFIG_VERSION + +from dlc_octopus.schemas.base.findings import Finding, Severity +from dlc_octopus.schemas.project_layout.config.observations import ( + ConfigObservation, + FailedConfigObservation, + ValidConfigObservation, +) +from dlc_octopus.validation.config import validate_project_config + + +def test_validate_valid_project_config( + valid_project: Path, +) -> None: + config_path = valid_project / "config.yaml" + + observation, findings = validate_project_config( + config_path, + ) + + assert isinstance( + observation, + ValidConfigObservation, + ) + assert observation.config_path == config_path + assert observation.declared_project_path == str(valid_project) + assert isinstance( + observation.value, + ProjectConfig, + ) + assert observation.value.scorer == "test-scorer" + assert findings == () + + +def test_validate_project_config_does_not_repair_declared_path( + tmp_path: Path, + valid_config_data: dict, +) -> None: + config_path = tmp_path / "config.yaml" + declared_path = tmp_path / "declared-elsewhere" + + config_data = dict(valid_config_data) + config_data["project_path"] = str(declared_path) + + write_config( + config_path, + config_data, + ) + + observation, findings = validate_project_config( + config_path, + ) + + assert isinstance( + observation, + ValidConfigObservation, + ) + assert observation.declared_project_path == str(declared_path) + assert observation.value.project_path == declared_path + assert findings == () + + +def _validate_with_null_keys( + tmp_path: Path, valid_config_data: dict, *fields: str +) -> tuple[ConfigObservation, tuple[Finding, ...]]: + config_path = tmp_path / "config.yaml" + + write_config( + config_path, + {**valid_config_data, **dict.fromkeys(fields)}, + ) + + return validate_project_config( + config_path, + ) + + +def test_validate_project_config_accepts_a_legacy_null_key_as_deeplabcut_does( + tmp_path: Path, + valid_config_data: dict, +) -> None: + # As in DeepLabCut's own examples/openfield-Pranav-2018-10-30: `multianimalproject:` left bare. + observation, findings = _validate_with_null_keys(tmp_path, valid_config_data, "multianimalproject") + + assert isinstance( + observation, + ValidConfigObservation, + ) + assert observation.value.multianimalproject is False + assert [(str(f.code), f.severity, f.field_location, f.evidence) for f in findings] == [ + ("CONFIG_NULL_KEY_DEFAULTED", Severity.NOTE, ("multianimalproject",), {"default": False}) + ] + + +def test_each_defaulted_null_key_is_reported_once( + tmp_path: Path, + valid_config_data: dict, +) -> None: + _, findings = _validate_with_null_keys(tmp_path, valid_config_data, "skeleton", "multianimalproject") + reported = [(f.field_location, f.evidence["default"]) for f in findings] + + assert sorted(reported) == [(("multianimalproject",), False), (("skeleton",), [])] + + +def test_a_null_key_whose_field_accepts_none_is_not_reported( + tmp_path: Path, + valid_config_data: dict, +) -> None: + observation, findings = _validate_with_null_keys(tmp_path, valid_config_data, "identity") + + assert isinstance(observation, ValidConfigObservation) + assert observation.value.identity is None + assert findings == () + + +def test_validate_invalid_project_config_retains_raw_data( + invalid_project: Path, +) -> None: + config_path = invalid_project / "config.yaml" + + observation, findings = validate_project_config( + config_path, + ) + + assert isinstance( + observation, + FailedConfigObservation, + ) + assert observation.config_path == config_path + assert observation.raw_config is not None + assert np.isnan(observation.raw_config["pcutoff"]) + + assert findings + assert all(finding.code == "CONFIG_VALIDATION_ERROR" for finding in findings) + assert all(finding.severity == Severity.ERROR for finding in findings) + assert all(finding.schema_id == "dlc.project.config" for finding in findings) + assert any(finding.field_location == ("pcutoff",) for finding in findings) + + +def test_validate_missing_config_returns_read_failure( + tmp_path: Path, +) -> None: + config_path = tmp_path / "config.yaml" + + observation, findings = validate_project_config( + config_path, + ) + + assert isinstance( + observation, + FailedConfigObservation, + ) + assert observation.config_path == config_path + assert observation.raw_config is None + + assert len(findings) == 1 + assert findings[0].code == "CONFIG_READ_FAILED" + assert findings[0].severity == Severity.ERROR + assert findings[0].schema_id == "dlc.project.config" + assert findings[0].path == config_path + + +def test_validate_empty_config_returns_parse_failure( + tmp_path: Path, +) -> None: + config_path = tmp_path / "config.yaml" + config_path.write_text( + "", + encoding="utf-8", + ) + + observation, findings = validate_project_config( + config_path, + ) + + assert isinstance( + observation, + FailedConfigObservation, + ) + assert observation.raw_config is None + + assert len(findings) == 1 + assert findings[0].code == "CONFIG_PARSE_FAILED" + assert findings[0].severity == Severity.ERROR + assert findings[0].schema_id == "dlc.project.config" + + +def test_validate_project_config_does_not_modify_file( + valid_project: Path, +) -> None: + config_path = valid_project / "config.yaml" + + before = ( + config_path.read_bytes(), + config_path.stat().st_mtime_ns, + ) + + validate_project_config( + config_path, + ) + + after = ( + config_path.read_bytes(), + config_path.stat().st_mtime_ns, + ) + + assert after == before + + +def test_validate_config_from_a_newer_deeplabcut_is_reported_not_raised( + tmp_path: Path, + valid_config_data: dict, +) -> None: + """A config version with no registered migration escapes ``from_dict`` as a bare ValueError.""" + + config_path = tmp_path / "config.yaml" + + config_data = dict(valid_config_data) + config_data["config_version"] = CURRENT_CONFIG_VERSION + 2 + + write_config( + config_path, + config_data, + ) + + observation, findings = validate_project_config( + config_path, + ) + + assert isinstance( + observation, + FailedConfigObservation, + ) + assert observation.raw_config is not None + + assert len(findings) == 1 + assert findings[0].code == "CONFIG_LOAD_FAILED" + assert findings[0].severity == Severity.ERROR + assert findings[0].schema_id == "dlc.project.config" + assert findings[0].evidence["error_type"] == "ValueError" + assert "No migration registered" in findings[0].evidence["error_message"] + + +def _migration_findings_for(tmp_path: Path, valid_config_data: dict, **fields: object) -> list[Finding]: + config_data = dict(valid_config_data) + config_data.pop("config_version", None) + config_data.update(fields) + write_config(tmp_path / "config.yaml", config_data) + + observation, findings = validate_project_config(tmp_path / "config.yaml") + + assert isinstance(observation, ValidConfigObservation) + + return [finding for finding in findings if finding.field_location == ("config_version",)] + + +def test_a_config_at_the_current_version_reports_no_migration( + tmp_path: Path, + valid_config_data: dict, +) -> None: + assert _migration_findings_for(tmp_path, valid_config_data, config_version=CURRENT_CONFIG_VERSION) == [] + + +def test_an_older_config_migrated_up_is_reported( + tmp_path: Path, + valid_config_data: dict, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Uses DeepLabCut's registered ProjectConfig 0 -> 1 migration, with the current version patched to 1.""" + + monkeypatch.setattr(versioning, "CURRENT_CONFIG_VERSION", 1) + + (finding,) = _migration_findings_for(tmp_path, valid_config_data) + + assert finding.code == "CONFIG_VERSION_UPGRADED" + assert finding.severity == Severity.NOTE + assert finding.evidence == {"declared_version": 0, "loaded_version": 1} + + +def test_a_newer_config_migrated_down_is_reported( + tmp_path: Path, + valid_config_data: dict, +) -> None: + """DeepLabCut registers a ProjectConfig 1 -> 0 migration, so a version-1 config loads today as version 0.""" + + (finding,) = _migration_findings_for(tmp_path, valid_config_data, config_version=CURRENT_CONFIG_VERSION + 1) + + assert finding.code == "CONFIG_VERSION_DOWNGRADED" + assert finding.severity == Severity.WARNING + assert finding.evidence == { + "declared_version": CURRENT_CONFIG_VERSION + 1, + "loaded_version": CURRENT_CONFIG_VERSION, + } + + +def test_validate_project_config_takes_no_unused_project_root() -> None: + assert "project_root" not in inspect.signature(validate_project_config).parameters + + +_MISSING = object() + + +def _config_with(tmp_path: Path, valid_config_data: dict, **fields: object) -> Path: + data = dict(valid_config_data) + for field, value in fields.items(): + if value is _MISSING: + data.pop(field, None) + else: + data[field] = value + write_config(tmp_path / "config.yaml", data) + return tmp_path / "config.yaml" + + +@pytest.mark.parametrize( + ("bodyparts", "declared"), + [("", {"bodyparts": ""}), ([], {"bodyparts": []}), (_MISSING, {})], +) +def test_a_single_animal_config_without_bodyparts_declares_no_keypoints( + tmp_path: Path, valid_config_data: dict, bodyparts: object, declared: dict +) -> None: + observation, findings = validate_project_config(_config_with(tmp_path, valid_config_data, bodyparts=bodyparts)) + + assert isinstance(observation, ValidConfigObservation) # reported, not refused + (finding,) = findings + assert (str(finding.code), finding.severity, finding.field_location) == ( + "CONFIG_NO_KEYPOINTS", + Severity.WARNING, + ("bodyparts",), + ) + assert finding.evidence == {"multianimal_project": False, "declared": declared} + + +@pytest.mark.parametrize("value", [[], _MISSING]) +def test_a_multi_animal_config_without_keypoints_declares_no_keypoints( + tmp_path: Path, valid_config_data: dict, value: object +) -> None: + path = _config_with( + tmp_path, + valid_config_data, + multianimalproject=True, + individuals=["a", "b"], + bodyparts="MULTI!", + multianimalbodyparts=value, + uniquebodyparts=value, + ) + + _, findings = validate_project_config(path) + + assert [(str(f.code), f.evidence["multianimal_project"]) for f in findings] == [("CONFIG_NO_KEYPOINTS", True)] + + +@pytest.mark.parametrize( + "fields", + [ + {"bodyparts": ["snout"]}, + { + "multianimalproject": True, + "individuals": ["a"], + "bodyparts": "MULTI!", + "multianimalbodyparts": ["snout"], + "uniquebodyparts": [], + }, + { + "multianimalproject": True, + "individuals": ["a"], + "bodyparts": "MULTI!", + "multianimalbodyparts": [], + "uniquebodyparts": ["arena"], + }, + ], +) +def test_a_config_with_any_keypoint_declares_some(tmp_path: Path, valid_config_data: dict, fields: dict) -> None: + # Control: the check fires on the absence of keypoints only. + _, findings = validate_project_config(_config_with(tmp_path, valid_config_data, **fields)) + + assert findings == () From f299b4c48992a7522509846b9128b6b43aec5bcd Mon Sep 17 00:00:00 2001 From: Cyril Achard Date: Thu, 26 Nov 2026 15:13:49 +0100 Subject: [PATCH 2/2] Adapt project config discovery and validation to dlccore - Rename the packages to dlccore.project, take the config schema from dlccore.config, and add the dlccore license header - Declare ConfigFindingCode without CONFIG_PROJECT_PATH_MISMATCH and CONFIG_PROJECT_PATH_NOT_ABSOLUTE, which land with project_path validation - Name the config schema, not DeepLabCut, as what reads, migrates and defaults a config, in docstrings and in three code descriptions - Export the validation context from validation - Add the valid_config_data and invalid_project fixtures; the latter's FIXME no longer names anyone - The closed-catalogue test now expects ConfigFindingCode too --- dlccore/project/discovery/config.py | 16 +++++++-- dlccore/project/schemas/base/finding_codes.py | 21 +++-------- dlccore/project/validation/config.py | 34 +++++++++++------- dlccore/project/validation/context.py | 20 ++++++++--- tests/conftest.py | 35 +++++++++++++++++++ .../discovery/test_config_discovery.py | 13 ++++++- tests/project/schemas/test_finding_codes.py | 3 +- .../validation/test_config_validation.py | 23 ++++++++---- 8 files changed, 120 insertions(+), 45 deletions(-) diff --git a/dlccore/project/discovery/config.py b/dlccore/project/discovery/config.py index 31367a7..3e36ae1 100644 --- a/dlccore/project/discovery/config.py +++ b/dlccore/project/discovery/config.py @@ -1,4 +1,14 @@ -# dlc_octopus/discovery/config.py +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + """Read a project's config file without interpreting or validating its content.""" from __future__ import annotations @@ -8,7 +18,7 @@ from pathlib import Path from typing import Any -from deeplabcut.core.config.utils import read_config_as_dict +from dlccore.config.utils import read_config_as_dict class RawConfigReadStatus(str, Enum): @@ -35,7 +45,7 @@ def discover_config_file( ) -> RawConfigRead: """Read a config file and record what was found, without validating it. - The existing DeepLabCut config reader performs YAML I/O. This function + ``dlccore.config`` performs the YAML I/O. This function does not migrate, validate, or interpret the loaded data beyond extracting the declared project path as written. """ diff --git a/dlccore/project/schemas/base/finding_codes.py b/dlccore/project/schemas/base/finding_codes.py index 0983de3..bbba2b6 100644 --- a/dlccore/project/schemas/base/finding_codes.py +++ b/dlccore/project/schemas/base/finding_codes.py @@ -121,14 +121,14 @@ class ConfigFindingCode(FindingCode): ) CONFIG_VERSION_UPGRADED = ( "CONFIG_VERSION_UPGRADED", - "The config declares an older config version; DeepLabCut migrated it in memory to the current one.", + "The config declares an older config version; the config schema migrated it in memory to the current one.", Severity.NOTE, ("declared_version", "loaded_version"), ) CONFIG_VERSION_DOWNGRADED = ( "CONFIG_VERSION_DOWNGRADED", - "The config declares a newer config version than this code reads; DeepLabCut migrated it down in memory, " - "which can drop fields.", + "The config declares a newer config version than this code reads; the config schema migrated it down in " + "memory, which can drop fields.", Severity.WARNING, ("declared_version", "loaded_version"), ) @@ -140,23 +140,10 @@ class ConfigFindingCode(FindingCode): ) CONFIG_NULL_KEY_DEFAULTED = ( "CONFIG_NULL_KEY_DEFAULTED", - "A config key is written with no value, so the DeepLabCut field default was used.", + "A config key is written with no value, so the config schema's field default was used.", Severity.NOTE, ("default",), ) - CONFIG_PROJECT_PATH_MISMATCH = ( - "CONFIG_PROJECT_PATH_MISMATCH", - "The project path declared in config.yaml does not match the project root observed. A declared path " - "probed as missing may also be an unreachable network location or a path from another platform.", - Severity.NOTE, - ("declared_project_path", "observed_project_root", "declared_path_probe", "error_type", "error_message"), - ) - CONFIG_PROJECT_PATH_NOT_ABSOLUTE = ( - "CONFIG_PROJECT_PATH_NOT_ABSOLUTE", - "The project path in config.yaml is missing, empty or relative, and cannot be compared with the project root.", - Severity.NOTE, - ("declared_project_path",), - ) def iter_finding_codes() -> tuple[FindingCode, ...]: diff --git a/dlccore/project/validation/config.py b/dlccore/project/validation/config.py index 847e1f0..393a392 100644 --- a/dlccore/project/validation/config.py +++ b/dlccore/project/validation/config.py @@ -1,31 +1,41 @@ -# dlc_octopus/validation/config.py +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + """Validate a project's config file against the canonical DLC schema.""" from __future__ import annotations from pathlib import Path -from deeplabcut.core.config import ProjectConfig from pydantic import JsonValue, ValidationError -from dlc_octopus.discovery.config import ( +from dlccore.config import ProjectConfig +from dlccore.project.discovery.config import ( RawConfigRead, RawConfigReadStatus, discover_config_file, ) -from dlc_octopus.schemas.base.finding_codes import ( +from dlccore.project.schemas.base.finding_codes import ( ConfigFindingCode, ) -from dlc_octopus.schemas.base.findings import ( +from dlccore.project.schemas.base.findings import ( Finding, ) -from dlc_octopus.schemas.locations import one_per_project -from dlc_octopus.schemas.project_layout.config.observations import ( +from dlccore.project.schemas.locations import one_per_project +from dlccore.project.schemas.project_layout.config.observations import ( ConfigObservation, FailedConfigObservation, ValidConfigObservation, ) -from dlc_octopus.schemas.project_layout.project import PROJECT_CONFIG +from dlccore.project.schemas.project_layout.project import PROJECT_CONFIG def validate_project_config( @@ -33,7 +43,7 @@ def validate_project_config( ) -> tuple[ConfigObservation, tuple[Finding, ...]]: """Read and validate a canonical DLC config without modifying it. - The existing DeepLabCut config reader performs YAML I/O. + ``dlccore.config`` performs the YAML I/O. ``ProjectConfig.from_dict`` performs validation against the canonical DLC schema. This function should not repair paths, modify the loaded model, or write @@ -120,7 +130,7 @@ def _migration_findings( raw_config: dict, config_path: Path, ) -> tuple[Finding, ...]: - """Report a config whose declared version DeepLabCut migrated in memory while loading it. + """Report a config whose declared version the config schema migrated in memory while loading it. A missing ``config_version`` is version 0, as DeepLabCut reads it. """ @@ -153,7 +163,7 @@ def _no_keypoints_findings( ) -> tuple[Finding, ...]: """Report a loaded config that declares no keypoints, with the keypoint fields as written. - DeepLabCut normalises ``""``, ``[]`` and a missing key alike, so only the raw read tells them apart. + The config schema normalises ``""``, ``[]`` and a missing key alike, so only the raw read tells them apart. """ fields = ("multianimalbodyparts", "uniquebodyparts") if config.multianimalproject else ("bodyparts",) @@ -180,7 +190,7 @@ def _null_key_defaulted_findings( raw_config: dict, config_path: Path, ) -> tuple[Finding, ...]: - """Report each key written with no value that DeepLabCut loaded as its field's default. + """Report each key written with no value that the config schema loaded as its field's default. A field that accepts ``None`` keeps it, so it is not reported. """ diff --git a/dlccore/project/validation/context.py b/dlccore/project/validation/context.py index 74ba8dd..5d38a2b 100644 --- a/dlccore/project/validation/context.py +++ b/dlccore/project/validation/context.py @@ -1,12 +1,22 @@ -from __future__ import annotations +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# -from deeplabcut.core.config import ProjectConfig +from __future__ import annotations -from dlc_octopus.schemas.base.core import FrozenModel -from dlc_octopus.schemas.project_layout.config.observations import ( +from dlccore.config import ProjectConfig +from dlccore.project.schemas.base.core import FrozenModel +from dlccore.project.schemas.project_layout.config.observations import ( ValidConfigObservation, ) -from dlc_octopus.schemas.snapshots import ProjectSnapshot +from dlccore.project.schemas.snapshots import ProjectSnapshot class ValidationContext(FrozenModel): diff --git a/tests/conftest.py b/tests/conftest.py index 8d169e3..317d919 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -15,9 +15,11 @@ from importlib import metadata from pathlib import Path +import numpy as np import pytest from dlccore.config import ProjectConfig +from dlccore.config.utils import write_config from dlccore.project.schemas.base.finding_codes import FindingCode, Severity from dlccore.project.schemas.snapshots import PROJECT_SNAPSHOT_VERSION @@ -189,6 +191,17 @@ def valid_project_config( ) +@pytest.fixture +def valid_config_data( + valid_project_config: ProjectConfig, +) -> dict: + """Return valid serialized config data that tests may modify.""" + + return valid_project_config.to_dict( + normalize=True, + ) + + @pytest.fixture def valid_project( tmp_path: Path, @@ -204,3 +217,25 @@ def valid_project( ) return tmp_path + + +@pytest.fixture +def invalid_project( + tmp_path: Path, + valid_config_data: dict, +) -> Path: + """Create a project with a canonically invalid config.""" + + (tmp_path / "videos").mkdir() + (tmp_path / "labeled-data").mkdir() + + invalid_data = dict(valid_config_data) + # FIXME: invalid for the current config schema only; a value invalid at every config version would be sturdier. + invalid_data["pcutoff"] = np.nan + + write_config( + tmp_path / "config.yaml", + invalid_data, + ) + + return tmp_path diff --git a/tests/project/discovery/test_config_discovery.py b/tests/project/discovery/test_config_discovery.py index 5cf181c..960394d 100644 --- a/tests/project/discovery/test_config_discovery.py +++ b/tests/project/discovery/test_config_discovery.py @@ -1,10 +1,21 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + from __future__ import annotations from pathlib import Path import pytest -from dlc_octopus.discovery.config import ( +from dlccore.project.discovery.config import ( RawConfigReadStatus, _declared_project_path, discover_config_file, diff --git a/tests/project/schemas/test_finding_codes.py b/tests/project/schemas/test_finding_codes.py index feeb202..8e40ab8 100644 --- a/tests/project/schemas/test_finding_codes.py +++ b/tests/project/schemas/test_finding_codes.py @@ -18,6 +18,7 @@ from pydantic import ValidationError from dlccore.project.schemas.base.finding_codes import ( + ConfigFindingCode, FindingCode, Severity, StructureFindingCode, @@ -201,7 +202,7 @@ def test_an_example_namespace_leaves_the_catalogue_after_its_test() -> None: def test_the_finding_code_catalogue_is_closed() -> None: """The catalogue is closed: adding a namespace is deliberate, so it fails here first.""" - assert set(FindingCode.__subclasses__()) == {StructureFindingCode} + assert set(FindingCode.__subclasses__()) == {StructureFindingCode, ConfigFindingCode} def test_severity_has_three_rungs() -> None: diff --git a/tests/project/validation/test_config_validation.py b/tests/project/validation/test_config_validation.py index c36ee94..5c9610d 100644 --- a/tests/project/validation/test_config_validation.py +++ b/tests/project/validation/test_config_validation.py @@ -1,3 +1,14 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + from __future__ import annotations import inspect @@ -5,17 +16,17 @@ import numpy as np import pytest -from deeplabcut.core.config import ProjectConfig, versioning -from deeplabcut.core.config.utils import write_config -from deeplabcut.core.config.versioning import CURRENT_CONFIG_VERSION -from dlc_octopus.schemas.base.findings import Finding, Severity -from dlc_octopus.schemas.project_layout.config.observations import ( +from dlccore.config import ProjectConfig, versioning +from dlccore.config.utils import write_config +from dlccore.config.versioning import CURRENT_CONFIG_VERSION +from dlccore.project.schemas.base.findings import Finding, Severity +from dlccore.project.schemas.project_layout.config.observations import ( ConfigObservation, FailedConfigObservation, ValidConfigObservation, ) -from dlc_octopus.validation.config import validate_project_config +from dlccore.project.validation.config import validate_project_config def test_validate_valid_project_config(