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
35 changes: 35 additions & 0 deletions dlccore/project/schemas/base/finding_codes.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,41 @@ def __new__(
return member


class StructureFindingCode(FindingCode):
"""Findings about the project's schema-defined layout."""

PROJECT_REQUIRED_NODE_MISSING = (
"PROJECT_REQUIRED_NODE_MISSING",
"A required project-layout node is missing.",
Severity.ERROR,
("resource_kind",),
)
PROJECT_SYMLINK_TARGET_MISSING = (
"PROJECT_SYMLINK_TARGET_MISSING",
"A project resource is a symlink whose target does not exist.",
Severity.ERROR,
("resource_kind", "raw_target", "absolute_target"),
)
PROJECT_SYMLINK_TARGET_WRONG_TYPE = (
"PROJECT_SYMLINK_TARGET_WRONG_TYPE",
"The symbolic-link target has an unexpected filesystem type.",
Severity.ERROR,
("resource_kind", "raw_target", "absolute_target", "target_kind"),
)
PROJECT_NODE_WRONG_TYPE = (
"PROJECT_NODE_WRONG_TYPE",
"A project resource exists at the expected location but has the wrong filesystem type.",
Severity.ERROR,
("resource_kind", "expected_type"),
)
PROJECT_NODE_UNREADABLE = (
"PROJECT_NODE_UNREADABLE",
"A project-layout node could not be read.",
Severity.ERROR,
("resource_kind", "error_type", "error_message"),
)


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

Expand Down
22 changes: 22 additions & 0 deletions dlccore/project/validation/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#
# 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 .requests import (
ProjectValidationRequest,
ResourceValidationRequest,
)
from .structure import validate_project_structure

__all__ = [
"ProjectValidationRequest",
"ResourceValidationRequest",
"validate_project_structure",
]
47 changes: 47 additions & 0 deletions dlccore/project/validation/requests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#
# 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 pydantic import model_validator
from typing_extensions import Self

from dlccore.project.schemas.base.core import FrozenModel
from dlccore.project.schemas.base.resources import (
ResourceKind,
)
from dlccore.project.schemas.base.validation import ValidationDepth


class ResourceValidationRequest(FrozenModel):
"""Validation requested for one semantic resource kind."""

kind: ResourceKind
depth: ValidationDepth


class ProjectValidationRequest(FrozenModel):
"""Explicit resource validation requested for one project inspection."""

resources: tuple[ResourceValidationRequest, ...] = ()

@model_validator(mode="after")
def validate_unique_resource_kinds(
self,
) -> Self:
"""Reject duplicate requests for the same resource kind."""

kinds = [request.kind for request in self.resources]

if len(kinds) != len(set(kinds)):
raise ValueError("Each resource kind may be requested at most once.")

return self
34 changes: 34 additions & 0 deletions dlccore/project/validation/results.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#
# 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 dlccore.project.schemas.base.core import FrozenModel
from dlccore.project.schemas.base.findings import Finding
from dlccore.project.schemas.base.validation import ValidationCheck


class ValidationResult(FrozenModel):
"""Findings and execution records produced by validation."""

findings: tuple[Finding, ...] = ()
checks: tuple[ValidationCheck, ...] = ()

def merge(
self,
other: ValidationResult,
) -> ValidationResult:
"""Combine two immutable validation results."""

return ValidationResult(
findings=(self.findings + other.findings),
checks=(self.checks + other.checks),
)
143 changes: 143 additions & 0 deletions dlccore/project/validation/structure.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
#
# 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

from dlccore.project.schemas.base.filesystem import (
DirectorySchema,
LayoutIndex,
NodeSchema,
)
from dlccore.project.schemas.base.finding_codes import StructureFindingCode
from dlccore.project.schemas.base.findings import Finding
from dlccore.project.schemas.base.observations import NodeStatus, ObservedNode, walk_observed_nodes
from dlccore.project.schemas.base.resources import ResourceManagement
from dlccore.project.schemas.base.symlinks import SymlinkTargetKind
from dlccore.project.schemas.locations import Location, node_location
from dlccore.project.schemas.project_layout.project import PROJECT_INDEX


def validate_project_structure(
project: ObservedNode,
*,
project_root: Path,
index: LayoutIndex = PROJECT_INDEX,
) -> tuple[Finding, ...]:
"""Validate an observed project against its layout schema.

Structural validation reports missing required nodes, nodes with the wrong
physical type, and nodes that could not be read. It does not interpret
config fields, validate file contents, or report unknown resources. A
known-unmanaged node is observed, not validated: it yields no finding here.
"""

findings: list[Finding] = []

for node in walk_observed_nodes(project):
node_schema = index.schemas.get(node.schema_id)

if node_schema is None:
raise ValueError(f"Observed node references unknown schema ID {node.schema_id!r}.")

if node_schema.management == ResourceManagement.KNOWN_UNMANAGED:
continue

finding = _finding_for_node(
node,
schema=node_schema,
project_root=project_root,
location=node_location(node.schema_id, node.project_relative_path, index=index),
)

if finding is not None:
findings.append(finding)

return tuple(findings)


def _finding_for_node(
node: ObservedNode,
*,
schema: NodeSchema,
project_root: Path,
location: Location,
) -> Finding | None:
"""Return a structural finding for one observed node, if needed."""

path = project_root / node.project_relative_path
evidence = {
"resource_kind": node.kind.value,
}

if node.status == NodeStatus.MISSING:
if not schema.required:
return None

return Finding(
code=StructureFindingCode.PROJECT_REQUIRED_NODE_MISSING,
**location,
path=path,
evidence=evidence,
)

if node.symlink is not None and node.symlink.target_kind == SymlinkTargetKind.MISSING:
return Finding(
code=StructureFindingCode.PROJECT_SYMLINK_TARGET_MISSING,
**location,
path=path,
evidence={
**evidence,
"raw_target": str(node.symlink.raw_target),
"absolute_target": str(node.symlink.absolute_target),
},
)

if node.symlink is not None and node.status == NodeStatus.WRONG_TYPE:
return Finding(
code=StructureFindingCode.PROJECT_SYMLINK_TARGET_WRONG_TYPE,
**location,
path=path,
evidence={
**evidence,
"raw_target": str(node.symlink.raw_target),
"absolute_target": str(node.symlink.absolute_target),
"target_kind": (node.symlink.target_kind.value),
},
)

if node.status == NodeStatus.WRONG_TYPE:
expected_type = "directory" if isinstance(schema, DirectorySchema) else "file"

return Finding(
code=StructureFindingCode.PROJECT_NODE_WRONG_TYPE,
**location,
path=path,
evidence={
**evidence,
"expected_type": expected_type,
},
)

if node.status == NodeStatus.UNREADABLE:
return Finding(
code=StructureFindingCode.PROJECT_NODE_UNREADABLE,
**location,
path=path,
evidence={
**evidence,
"error_type": node.traversal_error_type or node.probe.error_type,
"error_message": node.traversal_error_message or node.probe.error_message,
},
)

return None
9 changes: 7 additions & 2 deletions tests/project/schemas/test_finding_codes.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,12 @@
import pytest
from pydantic import ValidationError

from dlccore.project.schemas.base.finding_codes import FindingCode, Severity, iter_finding_codes
from dlccore.project.schemas.base.finding_codes import (
FindingCode,
Severity,
StructureFindingCode,
iter_finding_codes,
)
from dlccore.project.schemas.base.findings import Finding, Reach

_SCHEMA_ID = "dlc.videos.source_video"
Expand Down Expand Up @@ -196,7 +201,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__()) == set()
assert set(FindingCode.__subclasses__()) == {StructureFindingCode}


def test_severity_has_three_rungs() -> None:
Expand Down
80 changes: 80 additions & 0 deletions tests/project/validation/test_finding_schema_ids.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#
# 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 dlccore.project.schemas.base.filesystem import walk_schema
from dlccore.project.schemas.base.finding_codes import (
StructureFindingCode,
)
from dlccore.project.schemas.base.findings import Finding, Reach
from dlccore.project.schemas.locations import all_of, one_of, one_per_project
from dlccore.project.schemas.project_layout.project import PROJECT, PROJECT_INDEX

_DECLARED = frozenset(schema.schema_id for schema, _ in walk_schema(PROJECT))
_NODES = PROJECT_INDEX.schemas


# Moving a code to another node changes every consumer's scope, so each non-structural code's
# anchor is pinned here. Structure codes anchor at the node they are about.


def _undeclared_schema_ids(findings: tuple[Finding, ...]) -> set[str]:
return {finding.schema_id for finding in findings} - _DECLARED


def _misfit_reaches(findings: tuple[Finding, ...]) -> set[tuple[str, Reach]]:
"""Return the declared nodes whose emitted reach the layout location helpers would refuse."""

misfits: set[tuple[str, Reach]] = set()

for finding in findings:
node = _NODES.get(finding.schema_id)

if node is None:
continue

try:
if finding.reach is Reach.ONE_PER_PROJECT:
one_per_project(node)
elif finding.reach is Reach.ONE_OF:
one_of(node, finding.instance)
else:
all_of(node, finding.instance)
except ValueError:
misfits.add((finding.schema_id, finding.reach))

return misfits


def test_an_undeclared_schema_id_is_detected() -> None:
code = StructureFindingCode.PROJECT_NODE_UNREADABLE
planted = Finding(
code=code,
schema_id="dlc.not_declared_anywhere",
reach=Reach.ONE_PER_PROJECT,
evidence=dict.fromkeys(code.evidence_keys, "placeholder"),
)

assert _undeclared_schema_ids((planted,)) == {"dlc.not_declared_anywhere"}


def test_a_reach_that_does_not_fit_the_layout_is_detected() -> None:
code = StructureFindingCode.PROJECT_NODE_UNREADABLE
# The model accepts this, since it does not know the layout: only the helpers would refuse it.
planted = Finding(
code=code,
schema_id="dlc.videos.source_video",
reach=Reach.ONE_PER_PROJECT,
evidence=dict.fromkeys(code.evidence_keys, "placeholder"),
)

assert _misfit_reaches((planted,)) == {("dlc.videos.source_video", Reach.ONE_PER_PROJECT)}
Loading
Loading