Skip to content
Draft
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
88 changes: 88 additions & 0 deletions dlccore/project/discovery/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
#
# 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

from dataclasses import dataclass
from enum import Enum
from pathlib import Path
from typing import Any

from dlccore.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.

``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.
"""

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)
55 changes: 55 additions & 0 deletions dlccore/project/schemas/base/finding_codes.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,61 @@ 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; 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; the config schema 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 config schema's field default was used.",
Severity.NOTE,
("default",),
)


def iter_finding_codes() -> tuple[FindingCode, ...]:
"""Return every declared finding code, namespace by namespace."""

Expand Down
3 changes: 3 additions & 0 deletions dlccore/project/validation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -18,5 +19,7 @@
__all__ = [
"ProjectValidationRequest",
"ResourceValidationRequest",
"ValidationContext",
"build_validation_context",
"validate_project_structure",
]
221 changes: 221 additions & 0 deletions dlccore/project/validation/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
#
# 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 pydantic import JsonValue, ValidationError

from dlccore.config import ProjectConfig
from dlccore.project.discovery.config import (
RawConfigRead,
RawConfigReadStatus,
discover_config_file,
)
from dlccore.project.schemas.base.finding_codes import (
ConfigFindingCode,
)
from dlccore.project.schemas.base.findings import (
Finding,
)
from dlccore.project.schemas.locations import one_per_project
from dlccore.project.schemas.project_layout.config.observations import (
ConfigObservation,
FailedConfigObservation,
ValidConfigObservation,
)
from dlccore.project.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.

``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
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 the config schema 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.

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",)

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 the config schema 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,
}
Loading
Loading