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
52 changes: 52 additions & 0 deletions dlccore/project/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
#
# 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
#

"""Data validation-specific errors."""

from __future__ import annotations

from typing import TYPE_CHECKING

from dlccore.project.schemas.base.findings import Severity

if TYPE_CHECKING:
from dlccore.project.schemas.base.findings import Finding
from dlccore.project.schemas.snapshots import ProjectSnapshot


class ConfigUnavailableError(RuntimeError):
"""Raised when canonical project config data is unavailable."""


BLOCKING_SEVERITIES = frozenset({Severity.ERROR})


class ProjectValidationError(RuntimeError):
"""Raised when an inspected project contains blocking findings."""

def __init__(
self,
snapshot: ProjectSnapshot,
) -> None:
self.snapshot = snapshot
self.findings = _blocking_findings(snapshot)

codes = ", ".join(finding.code for finding in self.findings)

super().__init__(f"Project validation failed with {len(self.findings)} blocking finding(s): {codes}.")


def _blocking_findings(
snapshot: ProjectSnapshot,
) -> tuple[Finding, ...]:
"""Return the snapshot's findings whose severity is in ``BLOCKING_SEVERITIES``."""

return tuple(finding for finding in snapshot.findings if finding.severity in BLOCKING_SEVERITIES)
78 changes: 78 additions & 0 deletions dlccore/project/policy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
#
# 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
#

"""A consumer's policy over findings: the severity default, adjusted by the consumer's own finding codes.

The codes are the consumer's decision; these helpers only apply them.
"""

from __future__ import annotations

from collections.abc import Collection, Iterable

from dlccore.project.errors import BLOCKING_SEVERITIES
from dlccore.project.schemas.base.finding_codes import FindingCode
from dlccore.project.schemas.base.findings import Finding


def get_blocking_findings(
findings: Iterable[Finding],
*,
block: Collection[FindingCode] = (),
allow: Collection[FindingCode] = (),
) -> tuple[Finding, ...]:
"""Return the findings that block, in order: blocking severity by default, plus ``block``, minus ``allow``.

Args:
findings: The findings to filter, e.g. from ``findings_in_scope``.
block: Codes that block whatever their severity.
allow: Codes that never block, even at blocking severity.

Raises:
TypeError: If a code is not a ``FindingCode`` member, so that a renamed code fails where it is named.
ValueError: If a code is both blocked and allowed.
"""

_members(block)
_members(allow)

both = set(block) & set(allow)
if both:
raise ValueError(f"Codes both blocked and allowed: {sorted(both)}.")

return tuple(
finding
for finding in findings
if finding.code not in allow and (finding.severity in BLOCKING_SEVERITIES or finding.code in block)
)


def unhandled(findings: Iterable[Finding], handled: Collection[FindingCode]) -> tuple[Finding, ...]:
"""Return the findings whose code is not in ``handled``, in order.

Args:
findings: The findings to check.
handled: The codes the consumer maps; a mapping from each code to how it is handled also works, and only its
keys are read.

Raises:
TypeError: If a code is not a ``FindingCode`` member, so that a renamed code fails where it is named.
"""

_members(handled)

return tuple(finding for finding in findings if finding.code not in handled)


def _members(codes: Collection[FindingCode]) -> None:
strays = [code for code in codes if not isinstance(code, FindingCode)]
if strays:
raise TypeError(f"Name finding codes by their FindingCode members, not {strays!r}.")
83 changes: 83 additions & 0 deletions dlccore/project/schemas/base/finding_codes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
#
# 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
#

"""Finding vocabulary: severities, and the stable codes to emit.

Validation-check, baseline-check and validator-suite identifiers share the
same naming style but are separate namespaces.

Codes are grouped by subject rather than by emitting module, following the
``<SUBJECT>_<PROBLEM>`` convention.
"""

from __future__ import annotations

from enum import Enum
from itertools import chain


class Severity(str, Enum):
NOTE = "note"
WARNING = "warning"
ERROR = "error"


class FindingCode(str, Enum):
"""Base for every ``Finding.code`` namespace; declares no codes itself."""

# Render as the bare code, as ``enum.StrEnum`` would; it is 3.11+.
__str__ = str.__str__

description: str
severity: Severity
evidence_keys: tuple[str, ...]

def __new__(
cls,
code: str,
description: str,
severity: Severity,
evidence_keys: tuple[str, ...],
) -> FindingCode:
member = str.__new__(cls, code)
member._value_ = code
member.description = description
member.severity = severity
member.evidence_keys = tuple(evidence_keys)

return member


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

return tuple(chain.from_iterable(FindingCode.__subclasses__()))


def finding_code(value: str | FindingCode) -> FindingCode:
"""Return the declared code for one value, as read from serialized output.

Raises:
ValueError: If no namespace declares the value.
"""

if isinstance(value, FindingCode):
return value

for namespace in FindingCode.__subclasses__():
try:
return namespace(value)
except ValueError:
continue

declared = ", ".join(code.value for code in iter_finding_codes())

raise ValueError(f"Unknown finding code {value!r}. Declared codes are: {declared or '<NONE>'}.")
102 changes: 102 additions & 0 deletions dlccore/project/schemas/base/findings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
#
# 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
#

"""Simple diagnostic facts generated from walking through the project structure.

These are the main enablers for downstream reporting, consumption by GUI/CLI/LLM agents,
and offering actions based on the findings (e.g., "PROJECT_REQUIRED_NODE_MISSING" could trigger a prompt to
locate or create the missing file).
"""

from __future__ import annotations

from enum import Enum
from pathlib import Path

from pydantic import Field, JsonValue, model_validator
from typing_extensions import Self

from dlccore.project.schemas.base.core import FrozenModel, LayoutInstance, SchemaId
from dlccore.project.schemas.base.finding_codes import FindingCode, Severity, finding_code


class Reach(str, Enum):
"""Which instances of its layout node a finding is about."""

ONE_PER_PROJECT = "one_per_project"
ONE_OF = "one_of"
ALL_OF = "all_of"
# Outside any known project: the instance holds only the segments that are certain. Never in a snapshot.
UNROOTED = "unrooted"


class Finding(FrozenModel):
"""A structured diagnostic produced while inspecting or validating a project item.

Findings describe observable issues, warnings, or informational conditions
without modifying project data.
- Stable ``code`` values support programmatic handling, and carry the
human-readable text as ``code.description``
- ``schema_id``: the layout node it is about; consumers scope by it, never by ``path``
- ``reach``: whether it is about the only node of its kind, one instance, or every instance
- ``instance``: which instance of a repeated layout node it is about, as
project-relative path segments; ``()`` for ``ONE_PER_PROJECT``, a prefix for ``ALL_OF``, the certain
trailing segments for ``UNROOTED``
- ``path`` and ``field_location``: where in the project it was observed
- ``evidence``: the observations supporting it, e.g. "actual" vs "expected"
"""

code: FindingCode
severity: Severity
schema_id: SchemaId
reach: Reach
instance: LayoutInstance = ()
path: Path | None = None
field_location: tuple[str | int, ...] = ()
evidence: dict[str, JsonValue] = Field(default_factory=dict)

@model_validator(mode="before")
@classmethod
def _resolve_evidence(cls, data: object) -> object:
"""Resolve the code, take its severity, and require its declared evidence.

Raises:
ValueError: If the evidence the code declares is not all present.
"""

if not isinstance(data, dict) or data.get("code") is None:
return data

code = finding_code(data["code"])
evidence = data.get("evidence")
present = evidence.keys() if isinstance(evidence, dict) else ()
missing = tuple(key for key in code.evidence_keys if key not in present)

if missing:
raise ValueError(f"Finding {code.value} requires evidence keys {missing}.")

return {**data, "code": code, "severity": code.severity}

@model_validator(mode="after")
def _check_reach(self) -> Self:
"""Refuse a reach the instance contradicts.

Raises:
ValueError: If ``ONE_PER_PROJECT`` names an instance, or ``ONE_OF`` or ``UNROOTED`` names none.
"""

if self.reach is Reach.ONE_PER_PROJECT and self.instance:
raise ValueError(f"Reach ONE_PER_PROJECT names no instance, but got {self.instance!r}.")

if self.reach in {Reach.ONE_OF, Reach.UNROOTED} and not self.instance:
raise ValueError(f"Reach {self.reach.name} names one instance, but got none.")

return self
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ dynamic = [ "version" ]
dependencies = [
"numpy>=1.22.4",
"pandas>=2.3.3",
"pydantic>=2.1,<3",
"pydantic>=2.5.2,<3",
"ruamel-yaml>=0.16",
"typing-extensions",
]
Expand Down
46 changes: 46 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,15 @@
# Licensed under GNU Lesser General Public License v3.0
#

import gc
import os
from collections.abc import Callable
from pathlib import Path

import pytest

from dlccore.project.schemas.base.finding_codes import FindingCode, Severity


def _create_symlink_or_skip(
link: Path,
Expand Down Expand Up @@ -54,3 +57,46 @@ def stat_without_file_id(path: object, *args: object, **kwargs: object) -> os.st
return os.stat_result((result[0], 0, *result[2:]))

monkeypatch.setattr(os, "stat", stat_without_file_id)


def _declare_example_codes() -> type[FindingCode]:
class ExampleFindingCode(FindingCode):
"""Declared for one test; each real namespace lands with the check that first emits it."""

TEST_NODE_WRONG_TYPE = (
"TEST_NODE_WRONG_TYPE",
"A project resource exists at the expected location but has the wrong filesystem type.",
Severity.ERROR,
("resource_kind", "expected_type"),
)
TEST_NODE_UNREADABLE = (
"TEST_NODE_UNREADABLE",
"A project-layout node could not be read.",
Severity.ERROR,
("resource_kind", "error_type", "error_message"),
)

return ExampleFindingCode


_example_codes_declared = False


@pytest.fixture
def example_codes() -> type[FindingCode]:
"""A finding-code namespace that exists for one test only, so the catalogue every other test sees stays closed."""

global _example_codes_declared
_example_codes_declared = True

return _declare_example_codes()


def pytest_runtest_setup() -> None:
"""Collect the example namespace an earlier test declared; an enum class lingers in a reference cycle."""

global _example_codes_declared

if _example_codes_declared:
gc.collect()
_example_codes_declared = False
Loading
Loading